SlideShare a Scribd company logo
CopyrightPrismTech,2017
Angelo	Corsaro,	PhD
CTO,	ADLINK	Tech.	Inc.	
Co-Chair,	OMG	DDS-SIG	
angelo.corsaro@adlinktech.com
RUSTing
Partially Ordered
Rust Programming Ruminations
CopyrightPrismTech,2017
RUSTing is not a tutorial on the Rust programming
language.
I decided to create the RUSTing series as a way to
document and share programming idioms and techniques.
From time to time I’ll draw parallels with Haskell and Scala,
having some familiarity with one of them is useful but not
indispensable.
Prologue
CopyrightPrismTech,2017
Rust is a system programming
language that provides zero
cost high-level abstractions
and language-enforced
memory and concurrency
safety.
What is Rust?
CopyrightPrismTech,2017
Installing Rust is simple, just do*:
Getting Started
$ curl https://sh.rustup.rs -sSf | sh
I suggest you also install the documentation locally:
$ rustup component add rust-docs
Open the doc with:
$ rustup doc
CopyrightPrismTech,2017
Working with Monads…
CopyrightPrismTech,2017
The first monad one typically encounter is a List, but the
second one is usually the Maybe Monad
Like Scala, and differently from Haskell, Rust has named
the Monad used to model the “potential” presence of a
value as std::option::Option
Maybe is an Option
CopyrightPrismTech,2017
The Option Monad is an algebraic
data type with two variants,
Some(T) and None
The derive directives injects a
series of traits
The rest of the monad is
implemented in the impl clause
(see here)
The Option Monad
#[derive(Clone, Copy, PartialEq,
PartialOrd, Eq, Ord,
Debug, Hash)]
pub enum Option<T> {
None,
Some(T),
}
CopyrightPrismTech,2017
Depending on your background you may be familiar with at least
three ways of working with Option, and with Monad in generals
- map/flatMap
- map :: (a -> b) -> M a -> M b
- flatMap :: (a -> M b) -> M a -> M b
- Pattern Matching
- do construct in Haskell / for construct in Scala
Let’s investigate what the equivalents are in Rust
Working with an Option
CopyrightPrismTech,2017
Hardcore functional programmers live out of
map and flatMap
Rust’s Option type is equipped with a map
defined as:
In Rust’s , flatMap called and_then, is defined as:
The Orthodox Option
fn and_then<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> Option<U>
fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U
CopyrightPrismTech,2017
As a result the orthodox way of dealing with
options is to use map and and_then:
The Orthodox Option
let a = Some(18);
let b = Some(24);
let c = a.and_then(|x| {
b.map(|y| { x + y })
});
println!("{:?} + {:?} = {:?}", a, b, c);
[rust]: Some(18) + Some(24) = Some(42)
CopyrightPrismTech,2017
Another way to work with the Option type is
to use pattern matching as shown below:
Pattern Matching Option
let a = Some(18);
let b = Some(24);
let c = match a {
Some(x) => match b {
Some(y) => Some(x+y),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", a, b, c);
[rust]: Some(18) + Some(24) = Some(42)
CopyrightPrismTech,2017
That was easy. Let’s try with strings…
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.and_then(|a| {
t.map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
[…]
error[E0382]: use of moved value: `s`
error[E0382]: use of moved value: `t`
CopyrightPrismTech,2017
The reason why the apparently innocent example does not
compile has to do with Rust Ownership and Move semantics.
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.and_then(|a| {
t.map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
The moved t is freed here
The moved s is freed here
CopyrightPrismTech,2017
To avoid moving the value held by the option into the
lambda we have to use as_ref
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.as_ref().and_then(|a| {
t.as_ref().map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
[…]
[rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")
CopyrightPrismTech,2017
You have to watch out for moves also when using pattern
matching. As a consequence the following snippet also
suffers from “unintended” move
Move & Pattern Matching
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let u = match s {
Some(a) => match t {
Some(b) => Some(format!("{} {}", a, b)),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", s, t, u);
The moved s is freed here
The moved t is freed here
CopyrightPrismTech,2017
As we’ve seen with and_then/map the trick is to use
references. Please notice that as Option implements the
Copy trait we need to use the reference only on its
content — otherwise we would have had to match by &
Move & Pattern Matching
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let u = match s {
Some(ref a) => match t {
Some(ref b) => Some(format!("{} {}", a, b)),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", s, t, u);
CopyrightPrismTech,2017
If you are fond of Haskell’s do or Scala’s for construct
you can achieve a similar syntactical sugar by using
Rust’s iterators
Iterating an Option
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let mut u = None;
for a in s.iter() {
for b in t.iter() {
u = Some(format!("{} {}", a, b))
}
}
println!("{:?} + {:?} = {:?}", s, t, u);
This is not my favourite way
as I don’t like to use
mutability so casually.
It’d be much nicer if the
for-loop would allow to
return a value
[…]
[rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")

More Related Content

PPT
Clojure
PDF
re3 - modern regex syntax with a focus on adoption
PDF
Clojure night
DOCX
Latas bussines
PPTX
Software Design Thinking
PPT
PPTX
Advanced R Graphics
PDF
DDS and OPC UA Explained
Clojure
re3 - modern regex syntax with a focus on adoption
Clojure night
Latas bussines
Software Design Thinking
Advanced R Graphics
DDS and OPC UA Explained

Viewers also liked (6)

PDF
Getting Started with Vortex
PDF
Vortex II -- The Industrial IoT Connectivity Standard
PPTX
The Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
PDF
Fog Computing Defined
PDF
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...
PDF
Data Sharing in Extremely Resource Constrained Envionrments
Getting Started with Vortex
Vortex II -- The Industrial IoT Connectivity Standard
The Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
Fog Computing Defined
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...
Data Sharing in Extremely Resource Constrained Envionrments
Ad

Similar to RUSTing -- Partially Ordered Rust Programming Ruminations (20)

PPTX
Rust Intro
PPTX
Introduction To Rust part II Presentation
PDF
Le langage rust
PDF
Rust Intro @ Roma Rust meetup
PDF
The Rust Programming Language: an Overview
PDF
Reason - introduction to language and its ecosystem | Łukasz Strączyński
PDF
Степан Кольцов — Rust — лучше, чем C++
PDF
Rust - Fernando Borretti
PDF
Rust "Hot or Not" at Sioux
PDF
Coscup2021 - useful abstractions at rust and it's practical usage
PDF
Rust: Reach Further
PDF
Rustlabs Quick Start
PDF
Deep drive into rust programming language
PDF
Short intro to the Rust language
PPTX
The Rust Programming Language vs The C Programming Language
ODP
Rust Primer
PDF
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
PPTX
Why Rust? by Edd Barrett (codeHarbour December 2019)
PDF
Guaranteeing Memory Safety in Rust
PDF
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Rust Intro
Introduction To Rust part II Presentation
Le langage rust
Rust Intro @ Roma Rust meetup
The Rust Programming Language: an Overview
Reason - introduction to language and its ecosystem | Łukasz Strączyński
Степан Кольцов — Rust — лучше, чем C++
Rust - Fernando Borretti
Rust "Hot or Not" at Sioux
Coscup2021 - useful abstractions at rust and it's practical usage
Rust: Reach Further
Rustlabs Quick Start
Deep drive into rust programming language
Short intro to the Rust language
The Rust Programming Language vs The C Programming Language
Rust Primer
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
Why Rust? by Edd Barrett (codeHarbour December 2019)
Guaranteeing Memory Safety in Rust
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Ad

More from Angelo Corsaro (20)

PDF
Zenoh: The Genesis
PDF
zenoh: The Edge Data Fabric
PDF
Zenoh Tutorial
PDF
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
PDF
zenoh: zero overhead pub/sub store/query compute
PDF
zenoh -- the ZEro Network OverHead protocol
PDF
zenoh -- the ZEro Network OverHead protocol
PDF
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
PDF
Eastern Sicily
PDF
fog05: The Fog Computing Infrastructure
PDF
Cyclone DDS: Sharing Data in the IoT Age
PDF
fog05: The Fog Computing Platform
PDF
Programming in Scala - Lecture Four
PDF
Programming in Scala - Lecture Three
PDF
Programming in Scala - Lecture Two
PDF
Programming in Scala - Lecture One
PDF
The DDS Security Standard
PDF
The Data Distribution Service
PDF
DDS In Action Part II
PDF
DDS in Action -- Part I
Zenoh: The Genesis
zenoh: The Edge Data Fabric
Zenoh Tutorial
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
zenoh: zero overhead pub/sub store/query compute
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocol
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Eastern Sicily
fog05: The Fog Computing Infrastructure
Cyclone DDS: Sharing Data in the IoT Age
fog05: The Fog Computing Platform
Programming in Scala - Lecture Four
Programming in Scala - Lecture Three
Programming in Scala - Lecture Two
Programming in Scala - Lecture One
The DDS Security Standard
The Data Distribution Service
DDS In Action Part II
DDS in Action -- Part I

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Cloud computing and distributed systems.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Empathic Computing: Creating Shared Understanding
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation theory and applications.pdf
PDF
KodekX | Application Modernization Development
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Approach and Philosophy of On baking technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Cloud computing and distributed systems.
“AI and Expert System Decision Support & Business Intelligence Systems”
Empathic Computing: Creating Shared Understanding
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Programs and apps: productivity, graphics, security and other tools
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
KodekX | Application Modernization Development
Building Integrated photovoltaic BIPV_UPV.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Per capita expenditure prediction using model stacking based on satellite ima...
Approach and Philosophy of On baking technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

RUSTing -- Partially Ordered Rust Programming Ruminations

  • 2. CopyrightPrismTech,2017 RUSTing is not a tutorial on the Rust programming language. I decided to create the RUSTing series as a way to document and share programming idioms and techniques. From time to time I’ll draw parallels with Haskell and Scala, having some familiarity with one of them is useful but not indispensable. Prologue
  • 3. CopyrightPrismTech,2017 Rust is a system programming language that provides zero cost high-level abstractions and language-enforced memory and concurrency safety. What is Rust?
  • 4. CopyrightPrismTech,2017 Installing Rust is simple, just do*: Getting Started $ curl https://sh.rustup.rs -sSf | sh I suggest you also install the documentation locally: $ rustup component add rust-docs Open the doc with: $ rustup doc
  • 6. CopyrightPrismTech,2017 The first monad one typically encounter is a List, but the second one is usually the Maybe Monad Like Scala, and differently from Haskell, Rust has named the Monad used to model the “potential” presence of a value as std::option::Option Maybe is an Option
  • 7. CopyrightPrismTech,2017 The Option Monad is an algebraic data type with two variants, Some(T) and None The derive directives injects a series of traits The rest of the monad is implemented in the impl clause (see here) The Option Monad #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Option<T> { None, Some(T), }
  • 8. CopyrightPrismTech,2017 Depending on your background you may be familiar with at least three ways of working with Option, and with Monad in generals - map/flatMap - map :: (a -> b) -> M a -> M b - flatMap :: (a -> M b) -> M a -> M b - Pattern Matching - do construct in Haskell / for construct in Scala Let’s investigate what the equivalents are in Rust Working with an Option
  • 9. CopyrightPrismTech,2017 Hardcore functional programmers live out of map and flatMap Rust’s Option type is equipped with a map defined as: In Rust’s , flatMap called and_then, is defined as: The Orthodox Option fn and_then<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> Option<U> fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U
  • 10. CopyrightPrismTech,2017 As a result the orthodox way of dealing with options is to use map and and_then: The Orthodox Option let a = Some(18); let b = Some(24); let c = a.and_then(|x| { b.map(|y| { x + y }) }); println!("{:?} + {:?} = {:?}", a, b, c); [rust]: Some(18) + Some(24) = Some(42)
  • 11. CopyrightPrismTech,2017 Another way to work with the Option type is to use pattern matching as shown below: Pattern Matching Option let a = Some(18); let b = Some(24); let c = match a { Some(x) => match b { Some(y) => Some(x+y), None => None }, None => None }; println!("{:?} + {:?} = {:?}", a, b, c); [rust]: Some(18) + Some(24) = Some(42)
  • 12. CopyrightPrismTech,2017 That was easy. Let’s try with strings… Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.and_then(|a| { t.map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); […] error[E0382]: use of moved value: `s` error[E0382]: use of moved value: `t`
  • 13. CopyrightPrismTech,2017 The reason why the apparently innocent example does not compile has to do with Rust Ownership and Move semantics. Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.and_then(|a| { t.map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); The moved t is freed here The moved s is freed here
  • 14. CopyrightPrismTech,2017 To avoid moving the value held by the option into the lambda we have to use as_ref Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.as_ref().and_then(|a| { t.as_ref().map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); […] [rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")
  • 15. CopyrightPrismTech,2017 You have to watch out for moves also when using pattern matching. As a consequence the following snippet also suffers from “unintended” move Move & Pattern Matching let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let u = match s { Some(a) => match t { Some(b) => Some(format!("{} {}", a, b)), None => None }, None => None }; println!("{:?} + {:?} = {:?}", s, t, u); The moved s is freed here The moved t is freed here
  • 16. CopyrightPrismTech,2017 As we’ve seen with and_then/map the trick is to use references. Please notice that as Option implements the Copy trait we need to use the reference only on its content — otherwise we would have had to match by & Move & Pattern Matching let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let u = match s { Some(ref a) => match t { Some(ref b) => Some(format!("{} {}", a, b)), None => None }, None => None }; println!("{:?} + {:?} = {:?}", s, t, u);
  • 17. CopyrightPrismTech,2017 If you are fond of Haskell’s do or Scala’s for construct you can achieve a similar syntactical sugar by using Rust’s iterators Iterating an Option let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let mut u = None; for a in s.iter() { for b in t.iter() { u = Some(format!("{} {}", a, b)) } } println!("{:?} + {:?} = {:?}", s, t, u); This is not my favourite way as I don’t like to use mutability so casually. It’d be much nicer if the for-loop would allow to return a value […] [rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")