the new C++ ?
most loved programming language in:
2016, 2017 and 2018
- StackOverflow Survey
fn function (i: i32) -> i32 { i + 1 }
let closure_annotated = |i: i32| -> i32 { i + 1 };
let closure_inferred = |i | i + 1 ;
Control flexibility | |||
Double free | |||
Dangling pointers | |||
Buffer overflow | |||
Data races |
All variables are immutable by default
let elem = 5u8; //annotated as u8 type
let mut vec = Vec::new(); //growable array of something
vec.push(elem); // compiler knows now => Vec<u8>
fn main() {
let name = String::new();
save(name);
save(name); // Error: name was moved
}
fn save(name: String) {
// this is taking ownership
// then frees memory allocated for 'name'
}
Never have reader and writer at the same time
All is checked at compile time
fn main() {
let immutable_box = Box::new(5u32);
println!("immutable_box is {}", immutable_box); // 5
// *Move* the box (change the ownership)
// (and mutability)
let mut mutable_box = immutable_box;
// error! it's not owner
// println!("immutable_box is {}", immutable_box);
println!("mutable_box is {}", mutable_box); // 5
*mutable_box = 4;
println!("mutable_box now is {}", mutable_box); // 4
}
// Example 1
enum Event {
Load,
KeyPress(char),
Click { x: i64, y: i64 }
}
fn print_event(event: Event) {
match event {
Event::Load => println!("Loaded"),
Event::KeyPress(c) => println!("Key {} pressed", c),
Event::Click {x, y} => println!("Clicked at x={}, y={}", x, y),
}
}
// Example 2
fn load_images(paths: &[PathBuf]) -> Vec<Image> {
paths.iter()
.map(|path| Image::load(path))
.collect()
}
// Example 3
fn main() {
struct Dot { x: (u32, u32), y: u32 }
let dot = Dot { x: (1, 2), y: 3 };
let Dot { x: (a, b), y } = dot;
println!("a: {}, b: {}, y: {} ", a, b, y);
}
Generics
Traits
Closures
High order Functions
Macros
Builtins
Unit Tests
Fast code
Cross-lang interoparation
Lifetimes
Rust does not allow both at the same time
and verifies it
at compile time
|
|
---|---|
rustup | nvm |
cargo | npm |
rustfmt clippy |
~eslint |
Rust Playground | node REPL |
1..1_000 thanks