SlideShare una empresa de Scribd logo
1 de 93
Descargar para leer sin conexión
An Introduction to Rust
BIC Lazio Roma Casilina
February 16, 2016
Who we are
Claudio Capobianco
wbigger@gmail.com
@settevolte
Enrico Risa
enrico.risa@gmail.com
@wolf4ood
When and why I did meet Rust
Last September, within my startup.
We were looking for a replacement for C/C++ code for our
multi-platform software library for IoT.
We considered Rust, Go, and Swift.
Why a replacement for C/C++?
Not only verbosity and safety, but also:
- test were not straightforward
- dependences management was a nightmare
- in general, continuous integration was really difficult to
obtain
More problems to tackle...
Much of time spent on debugging.
Several languages mixed in the same project.
Often modern languages are easy to learn but stucks
when software become complex.
What is Rust
Sponsored by Mozilla Research
The 0.1 release was in January 2012
The 1.0.0 stable release was in May 2015, since then the
backward compatibility is guaranteed
Most programming language by StackOverflow survey:
third place in 2015, first place in 2016!
Rust goal
Ruby,
Javascript,
Python, ...C C++ Java
Control Safety
Rust goal
Rust
Ruby,
Javascript,
Python, ...C C++ Java
Control Safety
Just to mention a few:
and many others, look at https://www.rust-lang.org/en-US/friends.html
RUST is already in production!
RUST applications
Few of applications written completely in Rust:
Servo, a web browser engine by Mozilla
Rocket, a web framework, focus on easy-to-use and fast
Redox, full fledged Operating System, 100% Rust
Habitat, application automation framework
and many others, look at https://github.com/kud1ing/awesome-rust
Hello world!
fn main() {
// Print text to the console
println!("Hello World!");
}
Key concepts
Rust is born with the aim to balance control and security.
That is, in other words:
operate at low level with high-level constructs.
What control means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
}
data
length
capacity
elem
[0]
[1]
[2]
...
Stack Heap
vector
C++
string
What control means?
Ability to define abstractions that optimize away to
nothing.
What control means?
vector data
length
Java
capacity
[0]
...
data capacity
‘H’
‘e’
...
Ability to define abstractions that optimize away to
nothing.
What control means?
vector data
length
Java
capacity
[0]
...
data capacity
‘H’
‘e’
...
Ability to define abstractions that optimize away to
nothing.
What safety means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
data
length
capacity
elem
[0]
vector
C++
What safety means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
data
length
capacity
elem
[0]
vector
C++
What safety means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
data
length
capacity
elem
[0]
vector
C++
[0]
[1]
What safety means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
data
length
capacity
elem
[0]
vector
C++
[0]
[1]
dangling pointer!
What safety means?
void example() {
vector<string> vector;
…
auto& elem = vector[0];
vector.push_back(some_string);
cout << elem;
}
data
length
capacity
elem
[0]
vector
C++
[0]
[1]
aliasing
mutating
What safety means?
Problem with safety happens when we have a resource
that at the same time:
● has alias: more references to the resource
● is mutable: someone can modify the resource
That is (almost) the definition of data race.
What safety means?
Problem with safety happens when we have a resource
that at the same time:
● has alias: more references to the resource
● is mutable: someone can modify the resource
That is (almost) the definition of data race.
alias + mutable =
What about the garbage collector?
With the garbage collector:
● we lose control
● requires a runtime!
Anyway, it is insufficient to prevent data race or iterator
invalidation.
The Rust Way
Rust solution to achieve both control and safety is to push
as much as possible checks at compile time.
This is achieved mainly through the concepts of
● Ownership
● Borrowing
● Lifetimes
Ownership
Ownership
Ownership
Ownership
Green doesn’t own
the book anymore
and cannot use it
fn take(vec: Vec<i32>) {
//…
}
Ownership
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
}
data
length
capacity
vec
fn take(vec: Vec<i32>) {
//…
}
Ownership
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
}
data
length
capacity
[0]
[1]
vec
fn take(vec: Vec<i32>) {
//…
}
Ownership
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
}
data
length
capacity
[0]
[1]
vec
data
length
capacity
vec
take ownership
fn take(vec: Vec<i32>) {
//…
}
Ownership
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
}
data
length
capacity
[0]
[1]
vec
data
length
capacity
vec
fn take(vec: Vec<i32>) {
//…
}
Ownership
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
}
data
length
capacity
vec
cannot be used
because data is
no longer
available
fn take(vec: Vec<i32>) {
//…
}
Ownership - error
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
vec.push(3);
}
Borrowing
Borrowing with &T
one or more references to a resource
Borrowing with &T
read
read
read
&T
Borrowing with &T
Green can use its
book again
Borrowing with &mut T
exactly one mutable reference
Borrowing with &mut T
Borrowing with &mut T
&mut T
Borrowing with &mut T
&mut T
Borrowing with &mut T
Green can use its
book again
fn user(vec: &Vec<i32>) {
//…
}
Borrowing
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
} data
length
capacity
vec
Borrowing
data
length
capacity
[0]
[1]
vec
fn user(vec: &Vec<i32>) {
//…
}
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
}
Borrowing
data
length
capacity
[0]
[1]
vec
datavec
fn user(vec: &Vec<i32>) {
//…
}
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
}
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
}
fn user(vec: &Vec<i32>) {
//…
}
Borrowing
data
length
capacity
[0]
[1]
vec
datavec
shared ref to vec
loan out vec
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
}
fn user(vec: &Vec<i32>) {
vec.push(3);
}
Borrowing
data
length
capacity
[0]
[1]
vec
datavec
what happens if I
try to modify it?
loan out vec
Borrowing - error
fn lender() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
user(&vec);
}
fn user(vec: &Vec<i32>) {
vec.push(3);
}
Lifetimes
Lifetimes
Remember that the owner has always the ability to destroy
(deallocate) a resource!
In simplest cases, compiler recognize the problem and
refuse to compile.
In more complex scenarios compiler needs an hint.
Lifetimes
Lifetimes
&T
first borrowing
Lifetimes
&T
second
borrowing
!
Lifetimes
&T
dangling pointer!
Lifetime - first example
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - first example
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - first example
first borrowing
second borrowing
(we return something that is
not ours)
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - first example
first borrowing
second borrowing
(we return something that is
not ours)
we know that “s2” is valid as long
as “line” is valid, but compiler
doesn’t know
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - first example
refuse to
compile
fn skip_prefix(line: &str, prefix: &str) -> &str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - first example
Lifetime - example reviewed
fn skip_prefix<'a>(line: &'a str, prefix: &str) -> &'a str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
Lifetime - example reviewed
fn skip_prefix<'a>(line: &'a str, prefix: &str) -> &'a str {
let (s1,s2) = line.split_at(prefix.len());
s2
}
fn print_hello() {
let line = "lang:en=Hello World!";
let v;
{
let p = "lang:en=";
v = skip_prefix(line, p);
}
println!("{}", v);
}
borrowing source is now
explicit, through the
lifetime parameter
Hello World!
Other key concepts
Traits
“A trait is a language feature that tells the Rust compiler
about functionality a type must provide.”
https://doc.rust-lang.org
Rust is really conservative about what a generic type can
do!
Traits
fn is_equal<T>(a:T,b:T)->bool {
a==b
}
Traits
fn is_equal<T>(a:T,b:T)->bool {
a==b
}
generic type
Traits
fn is_equal<T>(a:T,b:T)->bool {
a==b
}
can T type be compared?
we are not sure...
fn is_equal<T>(a:T,b:T)->bool {
a==b
}
Traits
do not compile!
Traits
fn is_equal<T:PartialEq>(a:T,b:T)->bool {
a==b
}
type functionality is now
explicit
OK!
Lock data not code
The technique to lock data instead of code is widely used,
but generally is up to responsibility of developers.
“Lock data, not code” is enforced in Rust
No runtime
Unlike many other languages as Java, Go or JavaScript,
Rust doesn’t have a runtime environment.
This make much easier to write a library in Rust and
integrate it anywhere!
Option type
null does not exist in Rust
Rust uses the Option type instead.
enum Option<T> {
None,
Some(T),
}
let x = Some(7);
let y = None;
Result type
exceptions do not exist in Rust
Rust uses Result type instead.
enum Result<T, E> {
Ok(T),
Err(E),
}
let x = Ok(7);
let y = Error(“Too bad”);
Minimal core
Rust philosophy is to have a only few functionalities
built-in in the language, and delegates a lot to libraries.
It also uses macro! as a clean way to reduce boilerplate
code without “dirty” the language syntax.
According to me, this is one reason why it is loved
Ecosystem
Cargo
Rust’s package manager.
Manages dependencies and gives reproducible builds.
Cargo is one of the most powerful feature of Rust and it is
the result of an awesome community!
Cargo
In Cargo, each library is called “crate”.
Stabilization pipeline for features is very quickly and nightly
(as Rust language development itself).
“Stability without stagnation”
Crates
Can be either a binary or a library.
libc, types and bindings to native C functions
xml-rs, an XML library in pure Rust
time, utilities for working with time-related functions
serde, a generic serialization/deserialization framework
… and more like winapi, regex, url, rustc-serialize, etc.
Rustup is the Rust toolchain installer.
Easily switch between stable, beta, and nightly.
Cross-compiling is much simpler.
It is similar to Ruby's rbenv, Python's pyenv, or Node's nvm.
Install rustup by
curl https://sh.rustup.rs -sSf | sh
Rustup
Test
Rust objective is to ensure a high quality products.
Cargo has built-in a simple but efficient mechanism to write
and run test
cargo test
Test
#[test]
fn it_works() {
assert!(true)
}
Test
#[test]
fn it_works() {
assert!(false)
}
Test
#[test]
#[should_panic]
fn it_works() {
assert!(false)
}
Test can be also run on documented example!
Test
/// # Examples
/// ```
/// use adder::add_two;
/// assert_eq!(4, add_two(2));
/// ```
A full ecosystem
Formatter: rustfmt
Code completion: racer
Linter: clippy
Playground
https://play.rust-lang.org/
Community
Community
Rust has an active and amazing community.
https://this-week-in-rust.org/blog/2017/02/14/
Community
There are a lot of active channels, including:
forum, reddit, IRC, youtube, twitter, blog
And initiative like:
● crate of the week
● rust weekly
Credits
Youtube
The Rust Programming Language by Alex Crichton
SpeakerDeck
Hello, Rust! — An overview by Ivan Enderlin
This presentation is online!
Slideshare
https://www.slideshare.net/wbigger
Google Drive (public, comments enabled)
https://goo.gl/tKuHkI

Más contenido relacionado

La actualidad más candente

Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneC4Media
 
Deep drive into rust programming language
Deep drive into rust programming languageDeep drive into rust programming language
Deep drive into rust programming languageVigneshwer Dhinakaran
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming languagerobin_sy
 
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
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Codemotion
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsyann_s
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakSoroush Dalili
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
これから Haskell を書くにあたって
これから Haskell を書くにあたってこれから Haskell を書くにあたって
これから Haskell を書くにあたってTsuyoshi Matsudate
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 
Pwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakPwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakAbraham Aranguren
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricksGarethHeyes
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rustnikomatsakis
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Svetlin Nakov
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 

La actualidad más candente (20)

Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
Deep drive into rust programming language
Deep drive into rust programming languageDeep drive into rust programming language
Deep drive into rust programming language
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
 
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 programming-language
Rust programming-languageRust programming-language
Rust programming-language
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractions
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility Cloak
 
The Rust Programming Language
The Rust Programming LanguageThe Rust Programming Language
The Rust Programming Language
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
これから Haskell を書くにあたって
これから Haskell を書くにあたってこれから Haskell を書くにあたって
これから Haskell を書くにあたって
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
Pwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreakPwning mobile apps without root or jailbreak
Pwning mobile apps without root or jailbreak
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 

Destacado

Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming LanguageRobert 'Bob' Reyes
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011Patrick Walton
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 pramode_ce
 
Unba.se – San Diego Rust – march 2017 (abridged)
Unba.se – San Diego Rust – march 2017 (abridged)Unba.se – San Diego Rust – march 2017 (abridged)
Unba.se – San Diego Rust – march 2017 (abridged)Daniel Norman
 
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?Claudio Capobianco
 
Mozilla WebFWD Overview
Mozilla WebFWD OverviewMozilla WebFWD Overview
Mozilla WebFWD OverviewBrian King
 
Rust: история языка и контекст применения
Rust: история языка и контекст примененияRust: история языка и контекст применения
Rust: история языка и контекст примененияNikita Baksalyar
 
Почему Rust стоит вашего внимания
Почему Rust стоит вашего вниманияПочему Rust стоит вашего внимания
Почему Rust стоит вашего вниманияMichael Pankov
 
Mozilla + Rust at PCU Manila 02 DEC 2016
Mozilla + Rust at PCU Manila 02 DEC 2016Mozilla + Rust at PCU Manila 02 DEC 2016
Mozilla + Rust at PCU Manila 02 DEC 2016Robert 'Bob' Reyes
 
Antecedentes tdah
Antecedentes tdahAntecedentes tdah
Antecedentes tdahalma1111
 
Plataformas para crear diapositivas
Plataformas para crear diapositivasPlataformas para crear diapositivas
Plataformas para crear diapositivascris031
 
[jeeconf-2011] Java Platform Performance BoF
[jeeconf-2011] Java Platform Performance BoF[jeeconf-2011] Java Platform Performance BoF
[jeeconf-2011] Java Platform Performance BoFAleksey Shipilev
 
educación dijital
educación dijitaleducación dijital
educación dijitaldaivss
 

Destacado (18)

Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming Language
 
Rust All Hands Winter 2011
Rust All Hands Winter 2011Rust All Hands Winter 2011
Rust All Hands Winter 2011
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Unba.se – San Diego Rust – march 2017 (abridged)
Unba.se – San Diego Rust – march 2017 (abridged)Unba.se – San Diego Rust – march 2017 (abridged)
Unba.se – San Diego Rust – march 2017 (abridged)
 
Le competenze Agile: SCRUM
Le competenze Agile: SCRUMLe competenze Agile: SCRUM
Le competenze Agile: SCRUM
 
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?
Rust vs. Go: qual è il linguaggio più adatto al tuo progetto?
 
Mozilla WebFWD Overview
Mozilla WebFWD OverviewMozilla WebFWD Overview
Mozilla WebFWD Overview
 
Rust: история языка и контекст применения
Rust: история языка и контекст примененияRust: история языка и контекст применения
Rust: история языка и контекст применения
 
Erlang
ErlangErlang
Erlang
 
Почему Rust стоит вашего внимания
Почему Rust стоит вашего вниманияПочему Rust стоит вашего внимания
Почему Rust стоит вашего внимания
 
Mozilla + Rust at PCU Manila 02 DEC 2016
Mozilla + Rust at PCU Manila 02 DEC 2016Mozilla + Rust at PCU Manila 02 DEC 2016
Mozilla + Rust at PCU Manila 02 DEC 2016
 
Antecedentes tdah
Antecedentes tdahAntecedentes tdah
Antecedentes tdah
 
Proyecto de vida (1)
Proyecto de vida (1)Proyecto de vida (1)
Proyecto de vida (1)
 
Plataformas para crear diapositivas
Plataformas para crear diapositivasPlataformas para crear diapositivas
Plataformas para crear diapositivas
 
LOGO JGT final
LOGO JGT finalLOGO JGT final
LOGO JGT final
 
[jeeconf-2011] Java Platform Performance BoF
[jeeconf-2011] Java Platform Performance BoF[jeeconf-2011] Java Platform Performance BoF
[jeeconf-2011] Java Platform Performance BoF
 
educación dijital
educación dijitaleducación dijital
educación dijital
 
Sobre twitter
Sobre twitterSobre twitter
Sobre twitter
 

Similar a An introduction to Rust: the modern programming language to develop safe and efficient applications

Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Claudio Capobianco
 
Real-Time Web Programming with PrismTech Vortex Web
Real-Time Web Programming with PrismTech Vortex WebReal-Time Web Programming with PrismTech Vortex Web
Real-Time Web Programming with PrismTech Vortex WebADLINK Technology IoT
 
Building Real-Time Web Applications with Vortex-Web
Building Real-Time Web Applications with Vortex-WebBuilding Real-Time Web Applications with Vortex-Web
Building Real-Time Web Applications with Vortex-WebAngelo Corsaro
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...apidays
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...Fwdays
 
Does Java Have a Future After Version 8? (Belfast JUG April 2014)
Does Java Have a Future After Version 8? (Belfast JUG April 2014)Does Java Have a Future After Version 8? (Belfast JUG April 2014)
Does Java Have a Future After Version 8? (Belfast JUG April 2014)Garth Gilmour
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Wifi Security, or Descending into Depression and Drink
Wifi Security, or Descending into Depression and DrinkWifi Security, or Descending into Depression and Drink
Wifi Security, or Descending into Depression and DrinkSecurityTube.Net
 
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
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devicesLars Gregori
 
Pentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerPentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerBrian Hysell
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 

Similar a An introduction to Rust: the modern programming language to develop safe and efficient applications (20)

Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
C++ references
C++ referencesC++ references
C++ references
 
Introducing Rust
Introducing RustIntroducing Rust
Introducing Rust
 
Introducing Rust
Introducing RustIntroducing Rust
Introducing Rust
 
Real-Time Web Programming with PrismTech Vortex Web
Real-Time Web Programming with PrismTech Vortex WebReal-Time Web Programming with PrismTech Vortex Web
Real-Time Web Programming with PrismTech Vortex Web
 
Building Real-Time Web Applications with Vortex-Web
Building Real-Time Web Applications with Vortex-WebBuilding Real-Time Web Applications with Vortex-Web
Building Real-Time Web Applications with Vortex-Web
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...
Alexey Kupriyanenko "The State of Modern JavaScript and Web in 2020 - Real us...
 
Does Java Have a Future After Version 8? (Belfast JUG April 2014)
Does Java Have a Future After Version 8? (Belfast JUG April 2014)Does Java Have a Future After Version 8? (Belfast JUG April 2014)
Does Java Have a Future After Version 8? (Belfast JUG April 2014)
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Wifi Security, or Descending into Depression and Drink
Wifi Security, or Descending into Depression and DrinkWifi Security, or Descending into Depression and Drink
Wifi Security, or Descending into Depression and Drink
 
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
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devices
 
Pentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerPentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A Primer
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2
 

Último

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
 
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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
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
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 

Último (20)

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
 
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 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
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-...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

An introduction to Rust: the modern programming language to develop safe and efficient applications

  • 1. An Introduction to Rust BIC Lazio Roma Casilina February 16, 2016
  • 2. Who we are Claudio Capobianco wbigger@gmail.com @settevolte Enrico Risa enrico.risa@gmail.com @wolf4ood
  • 3. When and why I did meet Rust Last September, within my startup. We were looking for a replacement for C/C++ code for our multi-platform software library for IoT. We considered Rust, Go, and Swift.
  • 4. Why a replacement for C/C++? Not only verbosity and safety, but also: - test were not straightforward - dependences management was a nightmare - in general, continuous integration was really difficult to obtain
  • 5. More problems to tackle... Much of time spent on debugging. Several languages mixed in the same project. Often modern languages are easy to learn but stucks when software become complex.
  • 6. What is Rust Sponsored by Mozilla Research The 0.1 release was in January 2012 The 1.0.0 stable release was in May 2015, since then the backward compatibility is guaranteed Most programming language by StackOverflow survey: third place in 2015, first place in 2016!
  • 9. Just to mention a few: and many others, look at https://www.rust-lang.org/en-US/friends.html RUST is already in production!
  • 10. RUST applications Few of applications written completely in Rust: Servo, a web browser engine by Mozilla Rocket, a web framework, focus on easy-to-use and fast Redox, full fledged Operating System, 100% Rust Habitat, application automation framework and many others, look at https://github.com/kud1ing/awesome-rust
  • 11. Hello world! fn main() { // Print text to the console println!("Hello World!"); }
  • 12. Key concepts Rust is born with the aim to balance control and security. That is, in other words: operate at low level with high-level constructs.
  • 13. What control means? void example() { vector<string> vector; … auto& elem = vector[0]; } data length capacity elem [0] [1] [2] ... Stack Heap vector C++ string
  • 14. What control means? Ability to define abstractions that optimize away to nothing.
  • 15. What control means? vector data length Java capacity [0] ... data capacity ‘H’ ‘e’ ... Ability to define abstractions that optimize away to nothing.
  • 16. What control means? vector data length Java capacity [0] ... data capacity ‘H’ ‘e’ ... Ability to define abstractions that optimize away to nothing.
  • 17. What safety means? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } data length capacity elem [0] vector C++
  • 18. What safety means? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } data length capacity elem [0] vector C++
  • 19. What safety means? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } data length capacity elem [0] vector C++ [0] [1]
  • 20. What safety means? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } data length capacity elem [0] vector C++ [0] [1] dangling pointer!
  • 21. What safety means? void example() { vector<string> vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } data length capacity elem [0] vector C++ [0] [1] aliasing mutating
  • 22. What safety means? Problem with safety happens when we have a resource that at the same time: ● has alias: more references to the resource ● is mutable: someone can modify the resource That is (almost) the definition of data race.
  • 23. What safety means? Problem with safety happens when we have a resource that at the same time: ● has alias: more references to the resource ● is mutable: someone can modify the resource That is (almost) the definition of data race. alias + mutable =
  • 24. What about the garbage collector? With the garbage collector: ● we lose control ● requires a runtime! Anyway, it is insufficient to prevent data race or iterator invalidation.
  • 25. The Rust Way Rust solution to achieve both control and safety is to push as much as possible checks at compile time. This is achieved mainly through the concepts of ● Ownership ● Borrowing ● Lifetimes
  • 29. Ownership Green doesn’t own the book anymore and cannot use it
  • 30. fn take(vec: Vec<i32>) { //… } Ownership fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); } data length capacity vec
  • 31. fn take(vec: Vec<i32>) { //… } Ownership fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); } data length capacity [0] [1] vec
  • 32. fn take(vec: Vec<i32>) { //… } Ownership fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); } data length capacity [0] [1] vec data length capacity vec take ownership
  • 33. fn take(vec: Vec<i32>) { //… } Ownership fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); } data length capacity [0] [1] vec data length capacity vec
  • 34. fn take(vec: Vec<i32>) { //… } Ownership fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); } data length capacity vec cannot be used because data is no longer available
  • 35. fn take(vec: Vec<i32>) { //… } Ownership - error fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); vec.push(3); }
  • 37. Borrowing with &T one or more references to a resource
  • 39. Borrowing with &T Green can use its book again
  • 40. Borrowing with &mut T exactly one mutable reference
  • 44. Borrowing with &mut T Green can use its book again
  • 45. fn user(vec: &Vec<i32>) { //… } Borrowing fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); } data length capacity vec
  • 46. Borrowing data length capacity [0] [1] vec fn user(vec: &Vec<i32>) { //… } fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); }
  • 47. Borrowing data length capacity [0] [1] vec datavec fn user(vec: &Vec<i32>) { //… } fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); }
  • 48. fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); } fn user(vec: &Vec<i32>) { //… } Borrowing data length capacity [0] [1] vec datavec shared ref to vec loan out vec
  • 49. fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); } fn user(vec: &Vec<i32>) { vec.push(3); } Borrowing data length capacity [0] [1] vec datavec what happens if I try to modify it? loan out vec
  • 50. Borrowing - error fn lender() { let mut vec = Vec::new(); vec.push(1); vec.push(2); user(&vec); } fn user(vec: &Vec<i32>) { vec.push(3); }
  • 52. Lifetimes Remember that the owner has always the ability to destroy (deallocate) a resource! In simplest cases, compiler recognize the problem and refuse to compile. In more complex scenarios compiler needs an hint.
  • 57. Lifetime - first example fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); }
  • 58. Lifetime - first example fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); }
  • 59. fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); } Lifetime - first example first borrowing second borrowing (we return something that is not ours)
  • 60. fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); } Lifetime - first example first borrowing second borrowing (we return something that is not ours) we know that “s2” is valid as long as “line” is valid, but compiler doesn’t know
  • 61. fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); } Lifetime - first example refuse to compile
  • 62. fn skip_prefix(line: &str, prefix: &str) -> &str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); } Lifetime - first example
  • 63. Lifetime - example reviewed fn skip_prefix<'a>(line: &'a str, prefix: &str) -> &'a str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); }
  • 64. Lifetime - example reviewed fn skip_prefix<'a>(line: &'a str, prefix: &str) -> &'a str { let (s1,s2) = line.split_at(prefix.len()); s2 } fn print_hello() { let line = "lang:en=Hello World!"; let v; { let p = "lang:en="; v = skip_prefix(line, p); } println!("{}", v); } borrowing source is now explicit, through the lifetime parameter Hello World!
  • 66. Traits “A trait is a language feature that tells the Rust compiler about functionality a type must provide.” https://doc.rust-lang.org Rust is really conservative about what a generic type can do!
  • 69. Traits fn is_equal<T>(a:T,b:T)->bool { a==b } can T type be compared? we are not sure...
  • 72. Lock data not code The technique to lock data instead of code is widely used, but generally is up to responsibility of developers. “Lock data, not code” is enforced in Rust
  • 73. No runtime Unlike many other languages as Java, Go or JavaScript, Rust doesn’t have a runtime environment. This make much easier to write a library in Rust and integrate it anywhere!
  • 74. Option type null does not exist in Rust Rust uses the Option type instead. enum Option<T> { None, Some(T), } let x = Some(7); let y = None;
  • 75. Result type exceptions do not exist in Rust Rust uses Result type instead. enum Result<T, E> { Ok(T), Err(E), } let x = Ok(7); let y = Error(“Too bad”);
  • 76. Minimal core Rust philosophy is to have a only few functionalities built-in in the language, and delegates a lot to libraries. It also uses macro! as a clean way to reduce boilerplate code without “dirty” the language syntax. According to me, this is one reason why it is loved
  • 78. Cargo Rust’s package manager. Manages dependencies and gives reproducible builds. Cargo is one of the most powerful feature of Rust and it is the result of an awesome community!
  • 79. Cargo In Cargo, each library is called “crate”. Stabilization pipeline for features is very quickly and nightly (as Rust language development itself). “Stability without stagnation”
  • 80. Crates Can be either a binary or a library. libc, types and bindings to native C functions xml-rs, an XML library in pure Rust time, utilities for working with time-related functions serde, a generic serialization/deserialization framework … and more like winapi, regex, url, rustc-serialize, etc.
  • 81. Rustup is the Rust toolchain installer. Easily switch between stable, beta, and nightly. Cross-compiling is much simpler. It is similar to Ruby's rbenv, Python's pyenv, or Node's nvm. Install rustup by curl https://sh.rustup.rs -sSf | sh Rustup
  • 82. Test Rust objective is to ensure a high quality products. Cargo has built-in a simple but efficient mechanism to write and run test cargo test
  • 86. Test can be also run on documented example! Test /// # Examples /// ``` /// use adder::add_two; /// assert_eq!(4, add_two(2)); /// ```
  • 87. A full ecosystem Formatter: rustfmt Code completion: racer Linter: clippy
  • 90. Community Rust has an active and amazing community. https://this-week-in-rust.org/blog/2017/02/14/
  • 91. Community There are a lot of active channels, including: forum, reddit, IRC, youtube, twitter, blog And initiative like: ● crate of the week ● rust weekly
  • 92. Credits Youtube The Rust Programming Language by Alex Crichton SpeakerDeck Hello, Rust! — An overview by Ivan Enderlin
  • 93. This presentation is online! Slideshare https://www.slideshare.net/wbigger Google Drive (public, comments enabled) https://goo.gl/tKuHkI