SlideShare uma empresa Scribd logo
1 de 55
Rust Intro
by Artur Gavkaliuk
Mozilla
The language grew out of a personal project by Mozilla employee Graydon Hoare.
Mozilla began sponsoring the project in 2009 and announced it in 2010. The same
year, work shifted from the initial compiler (written in OCaml) to the self-hosting
compiler written in Rust. Known as rustc, it successfully compiled itself in 2011.
rustc uses LLVM as its back end.
Safe, concurrent, practical language
Rust is a general-purpose, multi-paradigm, compiled programming language.
It is designed to be a "safe, concurrent, practical language", supporting pure-
functional, imperative-procedural, and object-oriented styles.
Object oriented
Structs
Enums
Method Syntax
Generics
Traits
Structs
struct Point {
x: i32,
y: i32,
}
fn main() {
let origin = Point { x: 0, y: 0 }; // origin: Point
println!("The origin is at ({}, {})", origin.x, origin.y);
}
Enums
enum BoardGameTurn {
Move { squares: i32 },
Pass,
}
let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
Generics
struct Point<T> {
x: T,
y: T,
}
let int_origin = Point { x: 0, y: 0 };
let float_origin = Point { x: 0.0, y: 0.0 };
Method syntax
struct Circle {
x: f64,
y: f64,
radius: f64,
}
fn main() {
let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };
println!("{}", c.area());
}
Method syntax
impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
Traits
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
Traits
fn print_area<T: HasArea>(shape: T) {
println!("This shape has an area of {}", shape.area());
}
Functional
Functions
Function pointers
Type inference
Immutable by default
Option and Result
Pattern matching
Lambda functions
Functions
fn add_one(x: i32) -> i32 {
x + 1
}
Functions
fn add_one(x: i32) -> i32 {
x + 1;
}
We would get an error:
error: not all control paths return a value
fn add_one(x: i32) -> i32 {
x + 1;
}
help: consider removing this semicolon:
x + 1;
^
Functions
fn plus_one(i: i32) -> i32 {
i + 1
}
let f: fn(i32) -> i32 = plus_one;
let six = f(5);
Type inference
Rust has this thing called ‘type inference’. If it can figure out what the type of
something is, Rust doesn’t require you to actually type it out.
let x = 5; // x: i32
fn plus_one(i: i32) -> i32 {
i + 1
}
// without type inference
let f: fn(i32) -> i32 = plus_one;
// with type inference
let f = plus_one;
Mutability
let x = 5;
x = 10;
error: re-assignment of immutable variable `x`
x = 10;
^~~~~~~
Mutability
let mut x = 5; // mut x: i32
x = 10;
Option
pub enum Option<T> {
None,
Some(T),
}
Option
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 {
None
} else {
Some(numerator / denominator)
}
}
Result
enum Result<T, E> {
Ok(T),
Err(E)
}
fn divide(numerator: f64, denominator: f64) -> Result<f64, &'static str> {
if denominator == 0.0 {
Err("Can not divide by zero")
} else {
Ok(numerator / denominator)
}
}
Result
Pattern matching
let x = 5;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
4 => println!("four"),
5 => println!("five"),
_ => println!("something else"),
}
Pattern matching
One of the many advantages of match is it enforces ‘exhaustiveness checking’.
For example if we remove the last arm with the underscore _, the compiler will
give us an error:
error: non-exhaustive patterns: `_` not covered
Pattern matching
// The return value of the function is an option
let result = divide(2.0, 3.0);
// Pattern match to retrieve the value
match result {
// The division was valid
Some(x) => println!("Result: {}", x),
// The division was invalid
None => println!("Cannot divide by 0"),
}
Pattern matching
// The return value of the function is an Result<f64, &'static str>
let result = divide(2.0, 3.0);
// Pattern match to retrieve the value
match result {
// The division was valid
Ok(x) => println!("Result: {}", x),
// The division was invalid
Err(e) => println!(e),
}
Pattern matching
Again, the Rust compiler checks exhaustiveness, so it demands that you have a
match arm for every variant of the enum. If you leave one off, it will give you a
compile-time error unless you use _ or provide all possible arms.
Lambda functions
let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
Closures
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
Function pointers
fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
some_closure(1)
}
fn add_one(i: i32) -> i32 {
i + 1
}
let f = add_one;
let answer = call_with_one(&f);
assert_eq!(2, answer);
Memory Safe
The Stack and the Heap
Ownership
Borrowing
Lifetimes
The Stack
fn foo() {
let y = 5;
let z = 100;
}
fn main() {
let x = 42;
foo();
}
The Stack
fn foo() {
let y = 5;
let z = 100;
}
fn main() {
let x = 42; <-
foo();
}
Address Name Value
0 x 42
The Stack
fn foo() {
let y = 5;
let z = 100;
}
fn main() {
let x = 42;
foo(); <-
}
Address Name Value
2 z 1000
1 y 5
0 x 42
The Stack
fn foo() {
let y = 5;
let z = 100;
}
fn main() {
let x = 42;
foo();
} <-
Address Name Value
0 x 42
The Heap
fn main() {
let x = Box::new(5);
let y = 42;
}
Address Name Value
(230) - 1 5
... ... ...
1 y 42
0 x → (230) - 1
Ownership
let v = vec![1, 2, 3];
let v2 = v;
println!("v[0] is: {}", v[0]);
error: use of moved value: `v`
println!("v[0] is: {}", v[0]);
^
Ownership
fn take(v: Vec<i32>) {
// what happens here isn’t important.
}
let v = vec![1, 2, 3];
take(v);
println!("v[0] is: {}", v[0]);
Same error: ‘use of moved value’.
Borrowing
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);
Borrowing
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
// do stuff with v1 and v2
// return the answer
42
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let answer = foo(&v1, &v2);
// we can use v1 and v2 here!
&mut references
fn foo(v: &Vec<i32>) {
v.push(5);
}
let v = vec![];
foo(&v);
errors with:
error: cannot borrow immutable borrowed content `*v` as mutable
v.push(5);
^
&mut references
fn foo(v: &mut Vec<i32>) {
v.push(5);
}
let mut v = vec![];
foo(&mut v);
The Rules
First, any borrow must last for a scope no greater than that of the owner. Second,
you may have one or the other of these two kinds of borrows, but not both at the
same time:
one or more references (&T) to a resource,
exactly one mutable reference (&mut T).
Rust prevents data races at compile time
There is a ‘data race’ when two or more pointers access the same memory
location at the same time, where at least one of them is writing, and the operations
are not synchronized.
Lifetimes
1. I acquire a handle to some kind of resource.
2. I lend you a reference to the resource.
3. I decide I’m done with the resource, and deallocate it, while you still have your
reference.
4. You decide to use the resource.
Lifetimes
// implicit
fn foo(x: &i32) {
}
// explicit
fn bar<'a>(x: &'a i32) {
}
Lifetimes
You’ll also need explicit lifetimes when working with structs that contain
references.
Lifetimes
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let y = &5; // this is the same as `let _y = 5; let y = &_y;`
let f = Foo { x: y };
println!("{}", f.x);
}
Lifetimes
We need to ensure that any reference to a Foo cannot outlive the reference to an
i32 it contains.
Thinking in scopes
fn main() {
let y = &5; // -+ y goes into scope
// |
// stuff // |
// |
} // -+ y goes out of scope
Thinking in scopes
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let y = &5; // -+ y goes into scope
let f = Foo { x: y }; // -+ f goes into scope
// stuff // |
// |
} // -+ f and y go out of scope
Thinking in scopes
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
} // -+ x goes out of scope
Not Covered
Macros
Tests
Concurrency
Foreign Function Interface
Cargo
and much much more
Resources
The Rust Programming Language. Also known as “The Book”, The Rust Programming Language is the
most comprehensive resource for all topics related to Rust, and is the primary official document of the
language.
Rust by Example. A collection of self-contained Rust examples on a variety of topics, executable in-
browser.
Frequently asked questions.
The Rustonomicon. An entire book dedicated to explaining how to write unsafe Rust code. It is for
advanced Rust programmers.
rust-learning. A community-maintained collection of resources for learning Rust.
Thank You!

Mais conteúdo relacionado

Mais procurados

Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Edureka!
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingC4Media
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language安齊 劉
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015CODE BLUE
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneC4Media
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming languagerobin_sy
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC ServiceJessie Barnett
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquareApigee | Google Cloud
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Distributed tracing using open tracing &amp; jaeger 2
Distributed tracing using open tracing &amp; jaeger 2Distributed tracing using open tracing &amp; jaeger 2
Distributed tracing using open tracing &amp; jaeger 2Chandresh Pancholi
 

Mais procurados (20)

Rust programming-language
Rust programming-languageRust programming-language
Rust programming-language
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
Rust Primer
Rust PrimerRust Primer
Rust Primer
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Distributed tracing using open tracing &amp; jaeger 2
Distributed tracing using open tracing &amp; jaeger 2Distributed tracing using open tracing &amp; jaeger 2
Distributed tracing using open tracing &amp; jaeger 2
 

Destaque (18)

Caution this information can blow your head
Caution this information can blow your headCaution this information can blow your head
Caution this information can blow your head
 
Learning culture
Learning cultureLearning culture
Learning culture
 
Food Processor
Food ProcessorFood Processor
Food Processor
 
šK hádzaná detva prezentácia
šK hádzaná detva prezentáciašK hádzaná detva prezentácia
šK hádzaná detva prezentácia
 
Massage chair
Massage chairMassage chair
Massage chair
 
Panasonic air conditioners
Panasonic air conditionersPanasonic air conditioners
Panasonic air conditioners
 
Geospatial Analytics
Geospatial AnalyticsGeospatial Analytics
Geospatial Analytics
 
Kitchen Appliances India
Kitchen Appliances IndiaKitchen Appliances India
Kitchen Appliances India
 
Home Theater System
Home Theater SystemHome Theater System
Home Theater System
 
Best mobile phone
Best mobile phoneBest mobile phone
Best mobile phone
 
štrukturované produkty
štrukturované produktyštrukturované produkty
štrukturované produkty
 
Communication devices
Communication devicesCommunication devices
Communication devices
 
01 triangle new
01 triangle new01 triangle new
01 triangle new
 
Ingreso a exel
Ingreso a exelIngreso a exel
Ingreso a exel
 
Seri dreamweaver -_membuat_menu_bertingkat_tree_menu
Seri dreamweaver -_membuat_menu_bertingkat_tree_menuSeri dreamweaver -_membuat_menu_bertingkat_tree_menu
Seri dreamweaver -_membuat_menu_bertingkat_tree_menu
 
Analýza ŠK Hádzaná Detva
Analýza ŠK Hádzaná DetvaAnalýza ŠK Hádzaná Detva
Analýza ŠK Hádzaná Detva
 
Massage Chairs
Massage ChairsMassage Chairs
Massage Chairs
 
Sejam bem vindos
Sejam bem vindosSejam bem vindos
Sejam bem vindos
 

Semelhante a Rust Intro

golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Codemotion
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 pramode_ce
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
Introduction to go
Introduction to goIntroduction to go
Introduction to goJaehue Jang
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust languageGines Espada
 
Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with classTiago Babo
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingHoàng Lâm Huỳnh
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Hamidreza Soleimani
 

Semelhante a Rust Intro (20)

Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust language
 
Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with class
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Erlang
ErlangErlang
Erlang
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
Architecting Scalable Platforms in Erlang/OTP | Hamidreza Soleimani | Diginex...
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Rust Intro

  • 2. Mozilla The language grew out of a personal project by Mozilla employee Graydon Hoare. Mozilla began sponsoring the project in 2009 and announced it in 2010. The same year, work shifted from the initial compiler (written in OCaml) to the self-hosting compiler written in Rust. Known as rustc, it successfully compiled itself in 2011. rustc uses LLVM as its back end.
  • 3. Safe, concurrent, practical language Rust is a general-purpose, multi-paradigm, compiled programming language. It is designed to be a "safe, concurrent, practical language", supporting pure- functional, imperative-procedural, and object-oriented styles.
  • 5. Structs struct Point { x: i32, y: i32, } fn main() { let origin = Point { x: 0, y: 0 }; // origin: Point println!("The origin is at ({}, {})", origin.x, origin.y); }
  • 6. Enums enum BoardGameTurn { Move { squares: i32 }, Pass, } let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
  • 7. Generics struct Point<T> { x: T, y: T, } let int_origin = Point { x: 0, y: 0 }; let float_origin = Point { x: 0.0, y: 0.0 };
  • 8. Method syntax struct Circle { x: f64, y: f64, radius: f64, } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!("{}", c.area()); }
  • 9. Method syntax impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } }
  • 10. Traits trait HasArea { fn area(&self) -> f64; } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } }
  • 11. Traits fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); }
  • 12. Functional Functions Function pointers Type inference Immutable by default Option and Result Pattern matching Lambda functions
  • 13. Functions fn add_one(x: i32) -> i32 { x + 1 }
  • 14. Functions fn add_one(x: i32) -> i32 { x + 1; } We would get an error: error: not all control paths return a value fn add_one(x: i32) -> i32 { x + 1; } help: consider removing this semicolon: x + 1; ^
  • 15. Functions fn plus_one(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32 = plus_one; let six = f(5);
  • 16. Type inference Rust has this thing called ‘type inference’. If it can figure out what the type of something is, Rust doesn’t require you to actually type it out. let x = 5; // x: i32 fn plus_one(i: i32) -> i32 { i + 1 } // without type inference let f: fn(i32) -> i32 = plus_one; // with type inference let f = plus_one;
  • 17. Mutability let x = 5; x = 10; error: re-assignment of immutable variable `x` x = 10; ^~~~~~~
  • 18. Mutability let mut x = 5; // mut x: i32 x = 10;
  • 19. Option pub enum Option<T> { None, Some(T), }
  • 20. Option fn divide(numerator: f64, denominator: f64) -> Option<f64> { if denominator == 0.0 { None } else { Some(numerator / denominator) } }
  • 21. Result enum Result<T, E> { Ok(T), Err(E) }
  • 22. fn divide(numerator: f64, denominator: f64) -> Result<f64, &'static str> { if denominator == 0.0 { Err("Can not divide by zero") } else { Ok(numerator / denominator) } } Result
  • 23. Pattern matching let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), }
  • 24. Pattern matching One of the many advantages of match is it enforces ‘exhaustiveness checking’. For example if we remove the last arm with the underscore _, the compiler will give us an error: error: non-exhaustive patterns: `_` not covered
  • 25. Pattern matching // The return value of the function is an option let result = divide(2.0, 3.0); // Pattern match to retrieve the value match result { // The division was valid Some(x) => println!("Result: {}", x), // The division was invalid None => println!("Cannot divide by 0"), }
  • 26. Pattern matching // The return value of the function is an Result<f64, &'static str> let result = divide(2.0, 3.0); // Pattern match to retrieve the value match result { // The division was valid Ok(x) => println!("Result: {}", x), // The division was invalid Err(e) => println!(e), }
  • 27. Pattern matching Again, the Rust compiler checks exhaustiveness, so it demands that you have a match arm for every variant of the enum. If you leave one off, it will give you a compile-time error unless you use _ or provide all possible arms.
  • 28. Lambda functions let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1));
  • 29. Closures let num = 5; let plus_num = |x: i32| x + num; assert_eq!(10, plus_num(5));
  • 30. Function pointers fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(1) } fn add_one(i: i32) -> i32 { i + 1 } let f = add_one; let answer = call_with_one(&f); assert_eq!(2, answer);
  • 31. Memory Safe The Stack and the Heap Ownership Borrowing Lifetimes
  • 32. The Stack fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; foo(); }
  • 33. The Stack fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; <- foo(); } Address Name Value 0 x 42
  • 34. The Stack fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; foo(); <- } Address Name Value 2 z 1000 1 y 5 0 x 42
  • 35. The Stack fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; foo(); } <- Address Name Value 0 x 42
  • 36. The Heap fn main() { let x = Box::new(5); let y = 42; } Address Name Value (230) - 1 5 ... ... ... 1 y 42 0 x → (230) - 1
  • 37. Ownership let v = vec![1, 2, 3]; let v2 = v; println!("v[0] is: {}", v[0]); error: use of moved value: `v` println!("v[0] is: {}", v[0]); ^
  • 38. Ownership fn take(v: Vec<i32>) { // what happens here isn’t important. } let v = vec![1, 2, 3]; take(v); println!("v[0] is: {}", v[0]); Same error: ‘use of moved value’.
  • 39. Borrowing 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);
  • 40. Borrowing fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 { // do stuff with v1 and v2 // return the answer 42 } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let answer = foo(&v1, &v2); // we can use v1 and v2 here!
  • 41. &mut references fn foo(v: &Vec<i32>) { v.push(5); } let v = vec![]; foo(&v); errors with: error: cannot borrow immutable borrowed content `*v` as mutable v.push(5); ^
  • 42. &mut references fn foo(v: &mut Vec<i32>) { v.push(5); } let mut v = vec![]; foo(&mut v);
  • 43. The Rules First, any borrow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time: one or more references (&T) to a resource, exactly one mutable reference (&mut T).
  • 44. Rust prevents data races at compile time There is a ‘data race’ when two or more pointers access the same memory location at the same time, where at least one of them is writing, and the operations are not synchronized.
  • 45. Lifetimes 1. I acquire a handle to some kind of resource. 2. I lend you a reference to the resource. 3. I decide I’m done with the resource, and deallocate it, while you still have your reference. 4. You decide to use the resource.
  • 46. Lifetimes // implicit fn foo(x: &i32) { } // explicit fn bar<'a>(x: &'a i32) { }
  • 47. Lifetimes You’ll also need explicit lifetimes when working with structs that contain references.
  • 48. Lifetimes struct Foo<'a> { x: &'a i32, } fn main() { let y = &5; // this is the same as `let _y = 5; let y = &_y;` let f = Foo { x: y }; println!("{}", f.x); }
  • 49. Lifetimes We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.
  • 50. Thinking in scopes fn main() { let y = &5; // -+ y goes into scope // | // stuff // | // | } // -+ y goes out of scope
  • 51. Thinking in scopes struct Foo<'a> { x: &'a i32, } fn main() { let y = &5; // -+ y goes into scope let f = Foo { x: y }; // -+ f goes into scope // stuff // | // | } // -+ f and y go out of scope
  • 52. Thinking in scopes struct Foo<'a> { x: &'a i32, } fn main() { let x; // -+ x goes into scope // | { // | let y = &5; // ---+ y goes into scope let f = Foo { x: y }; // ---+ f goes into scope x = &f.x; // | | error here } // ---+ f and y go out of scope // | println!("{}", x); // | } // -+ x goes out of scope
  • 53. Not Covered Macros Tests Concurrency Foreign Function Interface Cargo and much much more
  • 54. Resources The Rust Programming Language. Also known as “The Book”, The Rust Programming Language is the most comprehensive resource for all topics related to Rust, and is the primary official document of the language. Rust by Example. A collection of self-contained Rust examples on a variety of topics, executable in- browser. Frequently asked questions. The Rustonomicon. An entire book dedicated to explaining how to write unsafe Rust code. It is for advanced Rust programmers. rust-learning. A community-maintained collection of resources for learning Rust.