SlideShare a Scribd company logo
1 of 36
Download to read offline
Intro To Rust
Why Another Programming
Language?
Why Another Programming
Language?
Memory safe without garbage collection
Compiled language. Blazingly fast!
Makes concurrency easy...ier
Tough but very kind compiler
Memory safety? How unsafe could
it be?
Accessing uninitialized data
Dangling pointers
Double free
Data races
Memory safety? How unsafe could
it be?
Accessing uninitialized data
Dangling pointers
Double free
Data races
Shared mutable state is the root of all
Ownership and Borrowing
Where magic happened
Ownership
Variable Bindings have the ownership of what
they bound to
fn foo() {
// v is the owner of the vector!
let v = vec![1, 2, 3];
}
Ownership
Ownership could be transfered
fn main() {
// v is the owner of the vector
let v = vec![1, 2, 3];
// Not anymore. The ownership has been transfered
// to i_want_v
let i_want_v = v;
println!("{}", v[0]); // Error!!!!
}
Ownership
Pass-by-Value is Pass-the-Ownership
fn take_ownership(v: Vec<i32>) {
println!("I got the ownership!!!");
}
fn main() {
// v is the owner of the vector
let v = vec![1, 2, 3];
// Now pass the ownership to take_ownership
take_ownership(v);
println!("{}", v[0]); // Error!!!!
}
Ownership
Pass-by-Value is Pass-the-Ownership
fn take_ownership(v: Vec<i32>) {
println!("I got the ownership!!!");
}
fn main() {
// v is the owner of the vector
let v = vec![1, 2, 3];
// Now pass the ownership to take_ownership
take_ownership(v);
println!("{}", v[0]); // Error!!!!
}
Unless you got Copy trait.
Ownership
Why so serious, compiler?
What if we don't care about ownership?
let v = vec![1, 2, 3];
let mut v2 = v;
v2.truncate(2); // Shorten the length to 2 elements long
println!("Let me access v[2]...{}", v[2]) // Error!!
Ownership
Why so serious, compiler?
Because we have stack and heap
Ownership
Why so serious, compiler?
Because we have stack and heap
Shared and mutable state is the root of all
Ownership
Why so serious, compiler?
Because we have stack and heap
Shared and mutable state is the root of all
Ownership
"Hey foo, I need that ownership back."
"Ok then."
fn foo(v1: Vec<i32>, v2: Vec<i32>)
-> (Vec<i32>, Vec<i32>, i32) {
// do stuff with v1 and v2...
// hand back ownership and the result of our function
(v1, v2, 42)
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let (v1, v2, answer) = foo(v1, v2);
References And Borrowing
The resources could be borrowed!
Borrowed by references
Shared Reference
Mutable Reference
References And Borrowing
Shared Reference &T
fn sum_vec(v: &Vec<i32>) -> i32 {
// Borrow a shared reference of a vector and
// calculating sum of all elements
return v.iter().fold(0, |a, &b| a + b);
}
fn main() {
let v = vec![1, 2, 3, 4];
let sum = sum_vec(&v);
println!("Sum of {:?} is {}", v, sum); // No Error!
}
References And Borrowing
Mutable Reference &mut T
fn add_element(v: &mut Vec<i32>, value: i32) {
v.push(value); // Mutate the vector
}
fn main() {
let mut v = vec![1, 2, 3, 4]; // mut is needed
add_element(&mut v, 5); // Borrowed as mutable
}
References And Borrowing
let mut v = vec![1, 2, 3];
let v2 = &mut v;
v2.truncate(2);
// Oh no! v doesn't know the referenced vector
// has changed!
println!("Let me access v[2]...{}", v[2]);
References And Borrowing
let mut v = vec![1, 2, 3];
let v2 = &mut v;
v2.truncate(2);
// Oh no! v doesn't know the referenced vector
// has changed!
println!("Let me access v[2]...{}", v[2]);
error: cannot borrow `v` as immutable because
it is also borrowed as mutable
References And Borrowing
The Rules
1. Any borrow must last for a scope no greater than
that of the owner.
2. Either one of the following, but not both at the
same time:
One or more references ( &T ) to the resource
Exactly one mutable reference ( &mut T ) to the
resource
References And Borrowing
The Rules
1. Any borrow must last for a scope no greater than
that of the owner.
2. Either one of the following, but not both at the
same time:
One or more references ( &T ) to the resource
Exactly one mutable reference ( &mut T ) to the
resource
Shared and mutable state is the root of all
References And Borrowing
The Rules
1. Any borrow must last for a scope no greater than
that of the owner.
2. Either one of the following, but not both at the
same time:
One or more references ( &T ) to the resource
Exactly one mutable reference ( &mut T ) to the
resource
Shared and mutable state is the root of all
References And Borrowing
The Rules
1. Any borrow must last for a scope no greater than
that of the owner.
2. Either one of the following, but not both at the
same time:
One or more references ( &T ) to the resource
Exactly one mutable reference ( &mut T ) to the
resource
Shared and mutable state is the root of all
References And Borrowing
Why so serious, compiler?
Iterator Invalidation
Use after free
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 1
let mut v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
v.push(34); // Might be reallocated!!
}
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 1
let mut v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
v.push(34); // Might be reallocated!!
}
error: cannot borrow `v` as mutable because it is also
borrowed as immutable
v.push(34);
^
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 2
// Copy elements to another vector
fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) {
for elem in from.iter() {
to.push(*elem);
}
}
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 2
// What if from and to are the same?
fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) {
for elem in from.iter() {
to.push(*elem);
}
}
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 2
// Dangling pointer!!!!
fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) {
for elem in from.iter() {
to.push(*elem); // Might be reallocated!!
}
}
References And Borrowing
Why so serious, compiler?
Iterator Invalidation ex. 2
// Dangling pointer!!!!
fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) {
for elem in from.iter() {
to.push(*elem); // Might be reallocated!!
}
}
error: cannot borrow `new_v` as mutable because it is also
borrowed as immutable
// Whew~
References And Borrowing
Why so serious, compiler?
Use after free
fn main() {
let y: &i32;
{
let x = 5;
y = &x; // borrow a reference from x
} // Oh no! x died! what is y now!?
println!("{}", y);
}
References And Borrowing
Why so serious, compiler?
Use after free
fn main() {
let y: &i32;
{
let x = 5;
y = &x; // borrow a reference from x
} // Oh no! x died! what is y now!?
println!("{}", y);
}
error: `x` does not live long enough
y = &x;
^
But What If I Need Both?
Concurrency in Rust
Shared nothing ( channel )
Shared Immutable Memory ( Arc<T> )
Mutation with Synchronization ( Arc<Mutex<T>> )
Conclusions
Rust combines high-level features with low-level
control
Rust gives strong safety guarantees beyond what
GC can offer:
Deterministic destruction
Data race freedom
Iterator Invalidation

More Related Content

Viewers also liked (15)

CACUSS2015presentation_FINAL
CACUSS2015presentation_FINALCACUSS2015presentation_FINAL
CACUSS2015presentation_FINAL
 
Jaw & Spider Couplings
Jaw & Spider CouplingsJaw & Spider Couplings
Jaw & Spider Couplings
 
NOV_DEC 2010 Connect (2)
NOV_DEC 2010 Connect (2)NOV_DEC 2010 Connect (2)
NOV_DEC 2010 Connect (2)
 
20.05.2014, Use of MSE for state privatizations, Nick Cousyn
20.05.2014, Use of MSE for state privatizations, Nick Cousyn20.05.2014, Use of MSE for state privatizations, Nick Cousyn
20.05.2014, Use of MSE for state privatizations, Nick Cousyn
 
14.12.2012, NEWSWIRE, Issue 252
14.12.2012, NEWSWIRE, Issue 25214.12.2012, NEWSWIRE, Issue 252
14.12.2012, NEWSWIRE, Issue 252
 
11.11.2015 organizational psychology management delgermend- npc mandal eng (1)
11.11.2015 organizational psychology management   delgermend- npc mandal eng (1)11.11.2015 organizational psychology management   delgermend- npc mandal eng (1)
11.11.2015 organizational psychology management delgermend- npc mandal eng (1)
 
02.05.2014, NEWSWIRE, Issue 323
02.05.2014, NEWSWIRE, Issue 32302.05.2014, NEWSWIRE, Issue 323
02.05.2014, NEWSWIRE, Issue 323
 
25.03.2011, NEWSWIRE, Issue 160
25.03.2011, NEWSWIRE, Issue 16025.03.2011, NEWSWIRE, Issue 160
25.03.2011, NEWSWIRE, Issue 160
 
gardnerlionnurse9
gardnerlionnurse9gardnerlionnurse9
gardnerlionnurse9
 
Phyto_Drip_Brochure
Phyto_Drip_BrochurePhyto_Drip_Brochure
Phyto_Drip_Brochure
 
26.04.2013, NEWSWIRE, Issue 271
26.04.2013, NEWSWIRE, Issue 27126.04.2013, NEWSWIRE, Issue 271
26.04.2013, NEWSWIRE, Issue 271
 
Procurement Article
Procurement ArticleProcurement Article
Procurement Article
 
21.11.2008, NEWSWIRE, Issue 47
21.11.2008, NEWSWIRE, Issue 4721.11.2008, NEWSWIRE, Issue 47
21.11.2008, NEWSWIRE, Issue 47
 
AUG_SEPT Connect
AUG_SEPT ConnectAUG_SEPT Connect
AUG_SEPT Connect
 
OACUHO
OACUHOOACUHO
OACUHO
 

Similar to Introduction to Rust Programming Language

An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Claudio Capobianco
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...Andrey Upadyshev
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsAndrey Upadyshev
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rustnikomatsakis
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devicesLars Gregori
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
Conjunctive queries
Conjunctive queriesConjunctive queries
Conjunctive queriesINRIA-OAK
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and Noteworthy
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and NoteworthyJava EE & Glass Fish User Group: Digital JavaEE 7 - New and Noteworthy
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and NoteworthyPeter Pilgrim
 
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.PilgrimJavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.PilgrimPayara
 
Lifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CLifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CFederico Tomassetti
 
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...HostedbyConfluent
 
Creating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfCreating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfShaiAlmog1
 

Similar to Introduction to Rust Programming Language (20)

An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devices
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
Conjunctive queries
Conjunctive queriesConjunctive queries
Conjunctive queries
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and Noteworthy
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and NoteworthyJava EE & Glass Fish User Group: Digital JavaEE 7 - New and Noteworthy
Java EE & Glass Fish User Group: Digital JavaEE 7 - New and Noteworthy
 
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.PilgrimJavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
 
Vue.js basics
Vue.js basicsVue.js basics
Vue.js basics
 
Lifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CLifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-C
 
Vertx
VertxVertx
Vertx
 
Vertx
VertxVertx
Vertx
 
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
 
Creating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdfCreating an Uber Clone - Part XII - Transcript.pdf
Creating an Uber Clone - Part XII - Transcript.pdf
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 

Introduction to Rust Programming Language

  • 3. Why Another Programming Language? Memory safe without garbage collection Compiled language. Blazingly fast! Makes concurrency easy...ier Tough but very kind compiler
  • 4. Memory safety? How unsafe could it be? Accessing uninitialized data Dangling pointers Double free Data races
  • 5. Memory safety? How unsafe could it be? Accessing uninitialized data Dangling pointers Double free Data races Shared mutable state is the root of all
  • 7. Ownership Variable Bindings have the ownership of what they bound to fn foo() { // v is the owner of the vector! let v = vec![1, 2, 3]; }
  • 8. Ownership Ownership could be transfered fn main() { // v is the owner of the vector let v = vec![1, 2, 3]; // Not anymore. The ownership has been transfered // to i_want_v let i_want_v = v; println!("{}", v[0]); // Error!!!! }
  • 9. Ownership Pass-by-Value is Pass-the-Ownership fn take_ownership(v: Vec<i32>) { println!("I got the ownership!!!"); } fn main() { // v is the owner of the vector let v = vec![1, 2, 3]; // Now pass the ownership to take_ownership take_ownership(v); println!("{}", v[0]); // Error!!!! }
  • 10. Ownership Pass-by-Value is Pass-the-Ownership fn take_ownership(v: Vec<i32>) { println!("I got the ownership!!!"); } fn main() { // v is the owner of the vector let v = vec![1, 2, 3]; // Now pass the ownership to take_ownership take_ownership(v); println!("{}", v[0]); // Error!!!! } Unless you got Copy trait.
  • 11. Ownership Why so serious, compiler? What if we don't care about ownership? let v = vec![1, 2, 3]; let mut v2 = v; v2.truncate(2); // Shorten the length to 2 elements long println!("Let me access v[2]...{}", v[2]) // Error!!
  • 12. Ownership Why so serious, compiler? Because we have stack and heap
  • 13. Ownership Why so serious, compiler? Because we have stack and heap Shared and mutable state is the root of all
  • 14. Ownership Why so serious, compiler? Because we have stack and heap Shared and mutable state is the root of all
  • 15. Ownership "Hey foo, I need that ownership back." "Ok then." fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { // do stuff with v1 and v2... // hand back ownership and the result of our function (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (v1, v2, answer) = foo(v1, v2);
  • 16. References And Borrowing The resources could be borrowed! Borrowed by references Shared Reference Mutable Reference
  • 17. References And Borrowing Shared Reference &T fn sum_vec(v: &Vec<i32>) -> i32 { // Borrow a shared reference of a vector and // calculating sum of all elements return v.iter().fold(0, |a, &b| a + b); } fn main() { let v = vec![1, 2, 3, 4]; let sum = sum_vec(&v); println!("Sum of {:?} is {}", v, sum); // No Error! }
  • 18. References And Borrowing Mutable Reference &mut T fn add_element(v: &mut Vec<i32>, value: i32) { v.push(value); // Mutate the vector } fn main() { let mut v = vec![1, 2, 3, 4]; // mut is needed add_element(&mut v, 5); // Borrowed as mutable }
  • 19. References And Borrowing let mut v = vec![1, 2, 3]; let v2 = &mut v; v2.truncate(2); // Oh no! v doesn't know the referenced vector // has changed! println!("Let me access v[2]...{}", v[2]);
  • 20. References And Borrowing let mut v = vec![1, 2, 3]; let v2 = &mut v; v2.truncate(2); // Oh no! v doesn't know the referenced vector // has changed! println!("Let me access v[2]...{}", v[2]); error: cannot borrow `v` as immutable because it is also borrowed as mutable
  • 21. References And Borrowing The Rules 1. Any borrow must last for a scope no greater than that of the owner. 2. Either one of the following, but not both at the same time: One or more references ( &T ) to the resource Exactly one mutable reference ( &mut T ) to the resource
  • 22. References And Borrowing The Rules 1. Any borrow must last for a scope no greater than that of the owner. 2. Either one of the following, but not both at the same time: One or more references ( &T ) to the resource Exactly one mutable reference ( &mut T ) to the resource Shared and mutable state is the root of all
  • 23. References And Borrowing The Rules 1. Any borrow must last for a scope no greater than that of the owner. 2. Either one of the following, but not both at the same time: One or more references ( &T ) to the resource Exactly one mutable reference ( &mut T ) to the resource Shared and mutable state is the root of all
  • 24. References And Borrowing The Rules 1. Any borrow must last for a scope no greater than that of the owner. 2. Either one of the following, but not both at the same time: One or more references ( &T ) to the resource Exactly one mutable reference ( &mut T ) to the resource Shared and mutable state is the root of all
  • 25. References And Borrowing Why so serious, compiler? Iterator Invalidation Use after free
  • 26. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 1 let mut v = vec![1, 2, 3]; for i in &v { println!("{}", i); v.push(34); // Might be reallocated!! }
  • 27. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 1 let mut v = vec![1, 2, 3]; for i in &v { println!("{}", i); v.push(34); // Might be reallocated!! } error: cannot borrow `v` as mutable because it is also borrowed as immutable v.push(34); ^
  • 28. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 2 // Copy elements to another vector fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) { for elem in from.iter() { to.push(*elem); } }
  • 29. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 2 // What if from and to are the same? fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) { for elem in from.iter() { to.push(*elem); } }
  • 30. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 2 // Dangling pointer!!!! fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) { for elem in from.iter() { to.push(*elem); // Might be reallocated!! } }
  • 31. References And Borrowing Why so serious, compiler? Iterator Invalidation ex. 2 // Dangling pointer!!!! fn append_vec(from: &Vec<i32>, to: mut &Vec<i32>) { for elem in from.iter() { to.push(*elem); // Might be reallocated!! } } error: cannot borrow `new_v` as mutable because it is also borrowed as immutable // Whew~
  • 32. References And Borrowing Why so serious, compiler? Use after free fn main() { let y: &i32; { let x = 5; y = &x; // borrow a reference from x } // Oh no! x died! what is y now!? println!("{}", y); }
  • 33. References And Borrowing Why so serious, compiler? Use after free fn main() { let y: &i32; { let x = 5; y = &x; // borrow a reference from x } // Oh no! x died! what is y now!? println!("{}", y); } error: `x` does not live long enough y = &x; ^
  • 34. But What If I Need Both?
  • 35. Concurrency in Rust Shared nothing ( channel ) Shared Immutable Memory ( Arc<T> ) Mutation with Synchronization ( Arc<Mutex<T>> )
  • 36. Conclusions Rust combines high-level features with low-level control Rust gives strong safety guarantees beyond what GC can offer: Deterministic destruction Data race freedom Iterator Invalidation