SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
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!")

Más contenido relacionado

Destacado

Destacado (6)

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

Similar a RUSTing -- Partially Ordered Rust Programming Ruminations

Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
gkgaur1987
 
2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer
tirlukachaitanya
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 

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

Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statistics
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
 
Go generics. what is this fuzz about?
Go generics. what is this fuzz about?Go generics. what is this fuzz about?
Go generics. what is this fuzz about?
 
2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg Mürk
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Write LESS. DO more.
Write LESS. DO more.Write LESS. DO more.
Write LESS. DO more.
 
Mapreduce in Search
Mapreduce in SearchMapreduce in Search
Mapreduce in Search
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
 
go.ppt
go.pptgo.ppt
go.ppt
 

Más de Angelo Corsaro

Más de Angelo Corsaro (20)

Zenoh: The Genesis
Zenoh: The GenesisZenoh: The Genesis
Zenoh: The Genesis
 
zenoh: The Edge Data Fabric
zenoh: The Edge Data Fabriczenoh: The Edge Data Fabric
zenoh: The Edge Data Fabric
 
Zenoh Tutorial
Zenoh TutorialZenoh Tutorial
Zenoh Tutorial
 
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair MonetisationData Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
 
zenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query computezenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query compute
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocol
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocol
 
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog ComputingBreaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
 
Eastern Sicily
Eastern SicilyEastern Sicily
Eastern Sicily
 
fog05: The Fog Computing Infrastructure
fog05: The Fog Computing Infrastructurefog05: The Fog Computing Infrastructure
fog05: The Fog Computing Infrastructure
 
Cyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT AgeCyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT Age
 
fog05: The Fog Computing Platform
fog05: The Fog Computing Platformfog05: The Fog Computing Platform
fog05: The Fog Computing Platform
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture One
 
The DDS Security Standard
The DDS Security StandardThe DDS Security Standard
The DDS Security Standard
 
The Data Distribution Service
The Data Distribution ServiceThe Data Distribution Service
The Data Distribution Service
 
DDS In Action Part II
DDS In Action Part IIDDS In Action Part II
DDS In Action Part II
 
DDS in Action -- Part I
DDS in Action -- Part IDDS in Action -- Part I
DDS in Action -- Part I
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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!")