SlideShare a Scribd company logo
Rust
Anthony Broad-Crawford
CTO @ Fooda
Rust is a systems
programming language
that runs blazingly fast,
prevents almost all
crashes*, and eliminates
data races.
rust
1. guaranteed memory safety
2. threads without dataraces
3. zero-cost abstractions (done at compile time)
4. trait-based generics
5. pattern matching
6. type inference
7. & more
Cargo is a tool that allows
Rust projects to declare
their various
dependencies, and ensure
that you'll always get a
repeatable build.
and tests ...
cargo
1. introduces conventions over configuration
2. declarative syntax for dependencies
3. declarative syntax for compilation profiles
4. easy execution of unit, integration, & benchmark
tests
our obligatory hello world
fn main() {
println!("Hello, world!");
}
//> Cargo run
//> Hello, world!
//
let's go create a hello
world with Cargo!
Using cargo to create projects
Rust's package manager
Usage:
cargo <command> [<args>...]
cargo [options]
Options:
-h, --help Display this message
-V, --version Print version info and exit
--list List installed commands
-v, --verbose Use verbose output
Some common cargo commands are:
build Compile the current project
clean Remove the target directory
doc Build this project's and its dependencies' documentation
new Create a new cargo project
run Build and execute src/main.rs
test Run the tests
bench Run the benchmarks
update Update dependencies listed in Cargo.lock
Primative types, Memory
safety & zero cost
abstractions
primatives
fn main() {
//integers
let i: i8 = 1; // i16, i32, i64, and i are available
//unsigned
let u: u8 = 2; // u16, u32, u64, and u are available
//floats
let f: f32 = 1.0; // f64 also available
//booleans
let b: bool = true; // false also available, duh
//string and characters
let c: char = 'a';
let s: &str = "hello world";
}
variable bindings
fn main() {
let x: int = 1; //explicitly declare type
let y = 2i; //type inference
let (a,b,c) = (1i,2i,3i); //variable declaration via patterns
let a = [1, 2, 3]; //array literals
let s = "hello"; //string literal
println!("*_^ x = {}, y = {}, a,b,c = {},{},{}", x,y,a,b,c);
}
//> Cargo run
//> *_^ x = 1, y = 2, a,b,c = 1,2,3
//
variable mutability
fn main() {
let x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//error: re-assignment of immutable variable `x`
// x = 10;
// ^~~~~~~
variable mutability
fn main() {
let mut x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//warning: value assigned to `x` is never read
// let mut x: int = 1;
// ^~~~~~~
The Rust compiler is SUPER helpful
fn main() {
let mut x: int = 1;
x = 10;
println!("The value of x is {}", x);
}
//Cargo run
//warning: value assigned to `x` is never read
// let mut x: int = 1;
// ^~~~~~~
stack vs. heap
fn main() {
let y: int = 1; //allocated on the stack
let x: Box<int> = Box::new(10); //allocated on the heap
println!("Heap {}, Stack {}", x, y);
}
//> Cargo run
//> Heap 10, Stack 1
//
heap allocation creates pointers
fn main() {
let x: Box<int> = box 10; //allocated on the heap
x = 11;
println!("The Heaps new value is {}, x");
}
//Cargo run
//error: mismatched types: expected `Box<int>`
// x = 11;
// ^~~~~~~
memory mutability
fn main() {
let x: Box<int> = box 10; //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
}
//Cargo run
//error: cannot assign to immutable dereference of `*x`
// x = 11;
// ^~~~~~~
memory mutability
fn main() {
let mut x: Box<int> = box 10; //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
}
//> Cargo run
//> The Heaps new value is 11
//
compiler protects you by owning de-allocation
fn main() {
let mut x: Box<int> = box::new(10); //allocated on the heap
*x = 11;
println!("The Heaps new value is {}, x");
//Scope for x ends here so the compiler adds the de-allocation
//free(x);
}
//> Cargo run
//> The Heaps new value is 11
//
There is no garbage
collection in Rust. The
compiler observes the
lifetime of a variable and
de-allocates it where it is
no longer used.
but these features don't
sum to the promised
memory safety
borrowing
fn main() {
// x is the owner of the integer, which is memory on the stack.
let x = 5;
// you may lend that resource to as many borrowers as you like
let y = &x;
let z = &x;
// functions can borrow too!
foo(&x);
// we can do this alllllll day!
let a = &x;
}
ownership is singular
fn main() {
let mut x = 5;
let y = &mut x; //mutability only allows one borrower
let z = &mut x; // ... no go
}
//> Cargo build
//> error: cannot borrow `x` as mutable more than once at a time
// let z = &mut x;
// ^~~~~~~~~~~~~~~
ownership can be transferred
fn main() {
let x: Box<i32> = Box::new(5);
let y = add_one(x);
println!("{}", y);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num
}
//> Cargo run
//> 6
//
ownership can be transferred back
fn main() {
let mut x: Box<i32> = Box::new(5);
x = add_one(x);
println!("{}", x);
}
fn add_one(mut num: Box<i32>) -> Box<i32> {
*num += 1;
num
}
//> Cargo run
//> 6
//
now THAT sums to to the
promised memory safety
and data race prevention
Other features of Rust
pattern matching
fn main() {
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
fn main() {
let x = 5;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
4 ... 7 => println!("4 through 7"),
_ => println!("anything"),
}
}
pattern matching
fn main(){
struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
match origin {
Point { x: x, .. } => println!("x is {}", x),
}
}
//> Cargo run
//> x is 0
//
iterators & adapters
fn main(){
for i in range(1i, 10i).filter(|&x| x % 2 == 0) {
println!("{}", i);
}
}
//> Cargo run
//> 2
//> 4
//> 6
//> 8
functions
//a function that takes and integer and returns an integer
fn add_one(x: i32) -> i32 {
x + 1
}
fn main(){
println!("1 plus 1 is {}", add_one(1));
}
//> Cargo run
//> 1 plus 1 is 2
//
closures
fn main() {
let add_one = |x| { 1 + x };
println!("The sum of 5 plus 1 is {}.", add_one(5));
}
//> Cargo run
//> The sum of 5 plus 1 is 6.
//
closures can be passed as params
//Generic function that takes a closure as an argument
fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 {
f(x) + f(x)
}
fn main() {
let result = twice(5, |x: i32| { x * x });
println!("And we have .... {}", result);
}
//> Cargo run
//> And we have .... 50
//
traits
struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
fn main() {
let c = Circle {x:0.0, y:1.0, radius: 2.0};
println!("The circles's radious is {}", c.area());
}
traits with generics
trait HasArea {
fn area(&self) -> f64;
}
fn print_area<T: HasArea>(shape: T) {
println!("This shape has an area of {}", shape.area());
}
fn main() {
let c = Circle {x:0.0, y:1.0, radius: 2.0};
print_area(c);
}
//> Cargo run
//> This shape has an area of 12.566371
//
So ... no classes?
concurrency
fn print_message(){
println!("Hello from within a thread!");
}
fn main() {
spawn(print_message);
}
//> Cargo run
//> Hello from within a thread!
//
concurrency and ownership
fn print_message(){
println!("Hello from within a thread!");
}
fn main() {
let x: int = 5;
spawn(move || print_message);
x = 10;
}
//> Cargo run
//> error: re-assignment of immutable variable `x`
// x = 10;
// ^~~~~~~
The promised land of the
Rust compiler :)
Cargo also has support for testing
1. unit testing
2. integration testing
3. benchmark testing
testing
#[test]
fn adding_one(){
let expected: int = 5;
let actual: int = 4;
assert_eq!(expected,actual);
}
//> Cargo Test
//> running 1 tests
//> test adding_one ... FAILED
//
testing an expected failure
#[test]
#[should_fail]
fn adding_one(){
let expected: int = 5;
let actual: int = 4;
assert_eq!(expected,actual);
}
//> Cargo Test
//> running 1 tests
//> test adding_one ... OK
//
making it pass
#[test]
fn adding_one(){
let expected: int = 5;
let actual: int = 5;
assert_eq!(expected,actual);
}
//> Cargo Test
//> running 1 tests
//> test adding_one ... OK
//
benchmark tests
#[bench]
fn bench_add_two(b: &mut Bencher) {
let add_one = |x| { 1 + x };
b.iter(|| add_one(2));
}
//> Cargo Test
//> running 1 tests
//> test tests::bench_add_two ... bench: 1 ns/iter (+/- 0)
//> test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured
//
As promised Rust
1. guarantees memory safety
2. threads without dataraces
3. zero-cost abstractions (done at compile time)
4. trait-based generics
5. pattern matching
6. type inference
7. & more
additional links
1. http://www.rust-lang.org
—Guide (nice intro)
—Reference (deeper articles)
2. http://rustbyexample.com
3. irc (super friendly and helpful lot)
lastly
curl -s https://static.rust-lang.org/rustup.sh | sudo sh
Questions?
Anthony Broad-Crawford
@broadcrawford
abc@anthonybroadcraword.com
650.691.5107 (c)

More Related Content

What's hot

Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
Jean Carlo Machado
 
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
Codemotion
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
robin_sy
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
C4Media
 
The Rust Programming Language
The Rust Programming LanguageThe Rust Programming Language
The Rust Programming Language
Mario Alexandro Santini
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
corehard_by
 
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: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
C4Media
 
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!
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devices
Lars Gregori
 
LXC, Docker, security: is it safe to run applications in Linux Containers?
LXC, Docker, security: is it safe to run applications in Linux Containers?LXC, Docker, security: is it safe to run applications in Linux Containers?
LXC, Docker, security: is it safe to run applications in Linux Containers?
Jérôme Petazzoni
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
Joris Bonnefoy
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
John-Alan Simmons
 
Rust Intro
Rust IntroRust Intro
Rust Intro
Arthur Gavkaluk
 
Rust
RustRust
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
Amal Mohan N
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
Aniruddha Chakrabarti
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
Platonov Sergey
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
Harshad Patil
 
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
Apigee | Google Cloud
 

What's hot (20)

Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
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
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
The Rust Programming Language
The Rust Programming LanguageThe Rust Programming Language
The Rust Programming Language
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
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: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
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...
 
Embedded Rust on IoT devices
Embedded Rust on IoT devicesEmbedded Rust on IoT devices
Embedded Rust on IoT devices
 
LXC, Docker, security: is it safe to run applications in Linux Containers?
LXC, Docker, security: is it safe to run applications in Linux Containers?LXC, Docker, security: is it safe to run applications in Linux Containers?
LXC, Docker, security: is it safe to run applications in Linux Containers?
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
 
Rust Intro
Rust IntroRust Intro
Rust Intro
 
Rust
RustRust
Rust
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
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
 

Viewers also liked

Rust 超入門
Rust 超入門Rust 超入門
Rust 超入門
Chris Birchall
 
今日から使おうSmalltalk
今日から使おうSmalltalk今日から使おうSmalltalk
今日から使おうSmalltalkSho Yoshida
 
Rust言語
Rust言語Rust言語
Rust言語
健太 田上
 
夢のある話をしようと思ったけど、やっぱり現実の話をする
夢のある話をしようと思ったけど、やっぱり現実の話をする夢のある話をしようと思ったけど、やっぱり現実の話をする
夢のある話をしようと思ったけど、やっぱり現実の話をする
Hidetsugu Takahashi
 
Smaltalk驚異の開発(私が使い続ける2012年の話)
Smaltalk驚異の開発(私が使い続ける2012年の話)Smaltalk驚異の開発(私が使い続ける2012年の話)
Smaltalk驚異の開発(私が使い続ける2012年の話)
Sho Yoshida
 
Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming Language
Robert 'Bob' Reyes
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
Paweł Rusin
 
Intro to introducing rust to ruby
Intro to introducing rust to rubyIntro to introducing rust to ruby
Intro to introducing rust to ruby
Anthony Broad-Crawford
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
nikomatsakis
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
nikomatsakis
 
Smalltalkと型について
Smalltalkと型についてSmalltalkと型について
Smalltalkと型について
Masashi Umezawa
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
Bruno Abinader
 
Introduction of Pharo 5.0
Introduction of Pharo 5.0Introduction of Pharo 5.0
Introduction of Pharo 5.0
Masashi Umezawa
 
Smalltalkだめ自慢
Smalltalkだめ自慢Smalltalkだめ自慢
Smalltalkだめ自慢
Masashi Umezawa
 
Machine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and CollenchymaMachine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and Collenchyma
Michael Hirn
 
データバインディング徹底攻略
データバインディング徹底攻略データバインディング徹底攻略
データバインディング徹底攻略Hiroyuki Mori
 
20150228 Realm超入門
20150228 Realm超入門20150228 Realm超入門
20150228 Realm超入門
Kei Ito
 
Realmについて
RealmについてRealmについて
Realmについて
Yuki Asano
 
Realmを使ってみた話
Realmを使ってみた話Realmを使ってみた話
Realmを使ってみた話
Takahito Morinaga
 
ユーザーを待たせないためにできること
ユーザーを待たせないためにできることユーザーを待たせないためにできること
ユーザーを待たせないためにできること
Tomoaki Imai
 

Viewers also liked (20)

Rust 超入門
Rust 超入門Rust 超入門
Rust 超入門
 
今日から使おうSmalltalk
今日から使おうSmalltalk今日から使おうSmalltalk
今日から使おうSmalltalk
 
Rust言語
Rust言語Rust言語
Rust言語
 
夢のある話をしようと思ったけど、やっぱり現実の話をする
夢のある話をしようと思ったけど、やっぱり現実の話をする夢のある話をしようと思ったけど、やっぱり現実の話をする
夢のある話をしようと思ったけど、やっぱり現実の話をする
 
Smaltalk驚異の開発(私が使い続ける2012年の話)
Smaltalk驚異の開発(私が使い続ける2012年の話)Smaltalk驚異の開発(私が使い続ける2012年の話)
Smaltalk驚異の開発(私が使い続ける2012年の話)
 
Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming Language
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Intro to introducing rust to ruby
Intro to introducing rust to rubyIntro to introducing rust to ruby
Intro to introducing rust to ruby
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Smalltalkと型について
Smalltalkと型についてSmalltalkと型について
Smalltalkと型について
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
 
Introduction of Pharo 5.0
Introduction of Pharo 5.0Introduction of Pharo 5.0
Introduction of Pharo 5.0
 
Smalltalkだめ自慢
Smalltalkだめ自慢Smalltalkだめ自慢
Smalltalkだめ自慢
 
Machine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and CollenchymaMachine Learning in Rust with Leaf and Collenchyma
Machine Learning in Rust with Leaf and Collenchyma
 
データバインディング徹底攻略
データバインディング徹底攻略データバインディング徹底攻略
データバインディング徹底攻略
 
20150228 Realm超入門
20150228 Realm超入門20150228 Realm超入門
20150228 Realm超入門
 
Realmについて
RealmについてRealmについて
Realmについて
 
Realmを使ってみた話
Realmを使ってみた話Realmを使ってみた話
Realmを使ってみた話
 
ユーザーを待たせないためにできること
ユーザーを待たせないためにできることユーザーを待たせないためにできること
ユーザーを待たせないためにできること
 

Similar to Rust-lang

Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
Daniele Esposti
 
ECMAScript 2015
ECMAScript 2015ECMAScript 2015
ECMAScript 2015
Sebastian Pederiva
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
jillisacebi75827
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
Frank Müller
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
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
Cory Forsyth
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
Fin Chen
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
Luka Zakrajšek
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
wkyra78
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
João Oliveira
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
Movel
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
Spam92
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
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
Codemotion
 

Similar to Rust-lang (20)

Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
ECMAScript 2015
ECMAScript 2015ECMAScript 2015
ECMAScript 2015
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
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
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
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
 

Recently uploaded

CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 

Recently uploaded (20)

CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 

Rust-lang

  • 3.
  • 4. Rust is a systems programming language that runs blazingly fast, prevents almost all crashes*, and eliminates data races.
  • 5. rust 1. guaranteed memory safety 2. threads without dataraces 3. zero-cost abstractions (done at compile time) 4. trait-based generics 5. pattern matching 6. type inference 7. & more
  • 6.
  • 7. Cargo is a tool that allows Rust projects to declare their various dependencies, and ensure that you'll always get a repeatable build.
  • 9. cargo 1. introduces conventions over configuration 2. declarative syntax for dependencies 3. declarative syntax for compilation profiles 4. easy execution of unit, integration, & benchmark tests
  • 10. our obligatory hello world fn main() { println!("Hello, world!"); } //> Cargo run //> Hello, world! //
  • 11. let's go create a hello world with Cargo!
  • 12. Using cargo to create projects Rust's package manager Usage: cargo <command> [<args>...] cargo [options] Options: -h, --help Display this message -V, --version Print version info and exit --list List installed commands -v, --verbose Use verbose output Some common cargo commands are: build Compile the current project clean Remove the target directory doc Build this project's and its dependencies' documentation new Create a new cargo project run Build and execute src/main.rs test Run the tests bench Run the benchmarks update Update dependencies listed in Cargo.lock
  • 13. Primative types, Memory safety & zero cost abstractions
  • 14. primatives fn main() { //integers let i: i8 = 1; // i16, i32, i64, and i are available //unsigned let u: u8 = 2; // u16, u32, u64, and u are available //floats let f: f32 = 1.0; // f64 also available //booleans let b: bool = true; // false also available, duh //string and characters let c: char = 'a'; let s: &str = "hello world"; }
  • 15. variable bindings fn main() { let x: int = 1; //explicitly declare type let y = 2i; //type inference let (a,b,c) = (1i,2i,3i); //variable declaration via patterns let a = [1, 2, 3]; //array literals let s = "hello"; //string literal println!("*_^ x = {}, y = {}, a,b,c = {},{},{}", x,y,a,b,c); } //> Cargo run //> *_^ x = 1, y = 2, a,b,c = 1,2,3 //
  • 16. variable mutability fn main() { let x: int = 1; x = 10; println!("The value of x is {}", x); } //Cargo run //error: re-assignment of immutable variable `x` // x = 10; // ^~~~~~~
  • 17. variable mutability fn main() { let mut x: int = 1; x = 10; println!("The value of x is {}", x); } //Cargo run //warning: value assigned to `x` is never read // let mut x: int = 1; // ^~~~~~~
  • 18. The Rust compiler is SUPER helpful fn main() { let mut x: int = 1; x = 10; println!("The value of x is {}", x); } //Cargo run //warning: value assigned to `x` is never read // let mut x: int = 1; // ^~~~~~~
  • 19. stack vs. heap fn main() { let y: int = 1; //allocated on the stack let x: Box<int> = Box::new(10); //allocated on the heap println!("Heap {}, Stack {}", x, y); } //> Cargo run //> Heap 10, Stack 1 //
  • 20. heap allocation creates pointers fn main() { let x: Box<int> = box 10; //allocated on the heap x = 11; println!("The Heaps new value is {}, x"); } //Cargo run //error: mismatched types: expected `Box<int>` // x = 11; // ^~~~~~~
  • 21. memory mutability fn main() { let x: Box<int> = box 10; //allocated on the heap *x = 11; println!("The Heaps new value is {}, x"); } //Cargo run //error: cannot assign to immutable dereference of `*x` // x = 11; // ^~~~~~~
  • 22. memory mutability fn main() { let mut x: Box<int> = box 10; //allocated on the heap *x = 11; println!("The Heaps new value is {}, x"); } //> Cargo run //> The Heaps new value is 11 //
  • 23. compiler protects you by owning de-allocation fn main() { let mut x: Box<int> = box::new(10); //allocated on the heap *x = 11; println!("The Heaps new value is {}, x"); //Scope for x ends here so the compiler adds the de-allocation //free(x); } //> Cargo run //> The Heaps new value is 11 //
  • 24. There is no garbage collection in Rust. The compiler observes the lifetime of a variable and de-allocates it where it is no longer used.
  • 25. but these features don't sum to the promised memory safety
  • 26. borrowing fn main() { // x is the owner of the integer, which is memory on the stack. let x = 5; // you may lend that resource to as many borrowers as you like let y = &x; let z = &x; // functions can borrow too! foo(&x); // we can do this alllllll day! let a = &x; }
  • 27. ownership is singular fn main() { let mut x = 5; let y = &mut x; //mutability only allows one borrower let z = &mut x; // ... no go } //> Cargo build //> error: cannot borrow `x` as mutable more than once at a time // let z = &mut x; // ^~~~~~~~~~~~~~~
  • 28. ownership can be transferred fn main() { let x: Box<i32> = Box::new(5); let y = add_one(x); println!("{}", y); } fn add_one(mut num: Box<i32>) -> Box<i32> { *num += 1; num } //> Cargo run //> 6 //
  • 29. ownership can be transferred back fn main() { let mut x: Box<i32> = Box::new(5); x = add_one(x); println!("{}", x); } fn add_one(mut num: Box<i32>) -> Box<i32> { *num += 1; num } //> Cargo run //> 6 //
  • 30. now THAT sums to to the promised memory safety and data race prevention
  • 32. pattern matching fn main() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } }
  • 33. pattern matching fn main() { let x = 5; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), 4 ... 7 => println!("4 through 7"), _ => println!("anything"), } }
  • 34. pattern matching fn main(){ struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x, .. } => println!("x is {}", x), } } //> Cargo run //> x is 0 //
  • 35. iterators & adapters fn main(){ for i in range(1i, 10i).filter(|&x| x % 2 == 0) { println!("{}", i); } } //> Cargo run //> 2 //> 4 //> 6 //> 8
  • 36. functions //a function that takes and integer and returns an integer fn add_one(x: i32) -> i32 { x + 1 } fn main(){ println!("1 plus 1 is {}", add_one(1)); } //> Cargo run //> 1 plus 1 is 2 //
  • 37. closures fn main() { let add_one = |x| { 1 + x }; println!("The sum of 5 plus 1 is {}.", add_one(5)); } //> Cargo run //> The sum of 5 plus 1 is 6. //
  • 38. closures can be passed as params //Generic function that takes a closure as an argument fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { f(x) + f(x) } fn main() { let result = twice(5, |x: i32| { x * x }); println!("And we have .... {}", result); } //> Cargo run //> And we have .... 50 //
  • 39. traits struct Circle { x: f64, y: f64, radius: f64, } trait HasArea { fn area(&self) -> f64; } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn main() { let c = Circle {x:0.0, y:1.0, radius: 2.0}; println!("The circles's radious is {}", c.area()); }
  • 40. traits with generics trait HasArea { fn area(&self) -> f64; } fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } fn main() { let c = Circle {x:0.0, y:1.0, radius: 2.0}; print_area(c); } //> Cargo run //> This shape has an area of 12.566371 //
  • 41. So ... no classes?
  • 42. concurrency fn print_message(){ println!("Hello from within a thread!"); } fn main() { spawn(print_message); } //> Cargo run //> Hello from within a thread! //
  • 43. concurrency and ownership fn print_message(){ println!("Hello from within a thread!"); } fn main() { let x: int = 5; spawn(move || print_message); x = 10; } //> Cargo run //> error: re-assignment of immutable variable `x` // x = 10; // ^~~~~~~
  • 44. The promised land of the Rust compiler :)
  • 45. Cargo also has support for testing 1. unit testing 2. integration testing 3. benchmark testing
  • 46. testing #[test] fn adding_one(){ let expected: int = 5; let actual: int = 4; assert_eq!(expected,actual); } //> Cargo Test //> running 1 tests //> test adding_one ... FAILED //
  • 47. testing an expected failure #[test] #[should_fail] fn adding_one(){ let expected: int = 5; let actual: int = 4; assert_eq!(expected,actual); } //> Cargo Test //> running 1 tests //> test adding_one ... OK //
  • 48. making it pass #[test] fn adding_one(){ let expected: int = 5; let actual: int = 5; assert_eq!(expected,actual); } //> Cargo Test //> running 1 tests //> test adding_one ... OK //
  • 49. benchmark tests #[bench] fn bench_add_two(b: &mut Bencher) { let add_one = |x| { 1 + x }; b.iter(|| add_one(2)); } //> Cargo Test //> running 1 tests //> test tests::bench_add_two ... bench: 1 ns/iter (+/- 0) //> test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured //
  • 50. As promised Rust 1. guarantees memory safety 2. threads without dataraces 3. zero-cost abstractions (done at compile time) 4. trait-based generics 5. pattern matching 6. type inference 7. & more
  • 51. additional links 1. http://www.rust-lang.org —Guide (nice intro) —Reference (deeper articles) 2. http://rustbyexample.com 3. irc (super friendly and helpful lot)