# Show & Tell: Rust ###### tags: `Show & Tell` --- ![rust](https://www.rust-lang.org/logos/rust-logo-512x512-blk.png) --- ## Ecosystem ``` bash rustup install stable rustup update ``` ``` bash cargo new --bin letstryrust cargo run ``` ``` toml [dependencies] chrono = "0.4" ``` --- ## Compiler = BFF ``` error[E0597]: `s` does not live long enough --> src/rule.rs:148:13 | 148 | return &s; | ^ borrowed value does not live long enough 149 | } | - borrowed value only lives until here | note: borrowed value must be valid for the lifetime 'a as defined on the function body at 146:1... ``` --- ## Variables ``` rust let foo = 5; let bar: usize = 0; ``` ``` rust let mut x = 5; x = 6; ``` ``` rust let spaces = " "; let spaces = spaces.len(); ``` --- ## Data Types * Integer: `u8`, `u16`, `u32`, `u64`, `i8`, `i16`, `i32`, `i64`, `usize`, `isize` * Float: `f32`, `f64` * Boolean: `bool` ---- ### Tuples ``` rust let t: (u8, f64, bool) = (5, 3.14, true); let x = t.0; let y = t.1; ``` ---- ### Arrays ``` rust let a = [1, 2, 3, 4, 5]; let x = a[0]; let y = a[4]; ``` ---- ### Structs ``` rust struct Meta { a: u8, b: f64, } let b = 3.14; let meta = Meta { a: 5, b, }; let a = meta.a; ``` ---- ### Enums ``` rust enum Example { Good, Bad(u8), Ugly(bool), } ``` ---- ### Empty ``` rust let a: () = (); ``` ---- ### Common Collections ``` rust let v: Vec<i32> = Vec::new(); let v = vec![1, 2, 3]; ``` ``` rust let s = String::new(); let s = String::from("initial contents"); let s = format!("Hello {}", name); let sp: &str = &s; ``` --- ## Functions ``` rust fn foo() {} fn bar(p1: bool) {} fn baz() -> u8 {} ``` --- ## Closures ``` rust let c = || 5; let c = |i| i + 5; ``` ``` rust let i = 5; let c = |j| i + j; ``` --- ## Flow ---- ### Branch ``` rust if foo < 5 { } else if bar > 9 { } else { } ``` ---- ### Loop ``` rust loop { } ``` ``` rust while foo < 5 { } ``` ``` rust for i in (1..4) { } ``` ``` rust let a = [1, 2, 3, 4, 5]; for i in a.iter() { } ``` ---- ### Pattern matching ``` rust let example: Example = ...; ``` ``` rust match example { Example::Good => { println!("Great!") }, Example::Bad(6) => println!("Not so bad"), Example::Bad(bad) if bad > 2 => println!("Oh, c'mon"), Example::Bad(bad) => println!("Better than {}", bad + 1), Example::Ugly(_) => println!("Uäh!"), _ => println!("WAT!"), } ``` ``` rust if let Example::Bad(bad) = example { } ``` --- ### Expressions ``` rust fn foo() -> i32 { 5 } ``` ``` rust let f = if foo < 5 { 3.14 } else { 2.71 }; ``` ``` rust let f = match foo { Some(foo) => 1.0 / foo, None => 0.0, }; ``` ``` rust let f = loop { if foo < 5 { break 3.14; } } ``` --- ## Generics ``` rust struct Point<T> { x: T, y: T, } let p: Point<f32> = Point { x: 3.14, y: 0.0 }; let p = Point { x: true, y: false }; ``` ``` rust let x: Option<f64> = Some(3.14); let x: Option<f64> = None; ``` ``` rust let x: Result<f64, String> = Ok(3.14); let x: Option<f64, String> = Err(...); ``` --- ## Ownership > * Each value in Rust has a variable that’s called its owner. > * There can only be one owner at a time. > * When the owner goes out of scope, the value will be dropped. ---- ## Move ``` rust let x = 5; let y = x; println!("x = {}", x); ``` ``` rust let x = String::from("hello"); let y = x; println!("x = {}", x); // Error: use of moved value: `x` ``` ---- ## Move cont. ``` rust fn doit(s: String) { println!("s = {}", s); } let x = String::from("hello"); doit(s); println!("x = {}", x); // Error: use of moved value: `x` ``` ``` rust fn doit(s: String) -> String { println!("s = {}", s); return s; } let x = String::from("hello"); let x = doit(s); println!("x = {}", x); ``` ---- ## Borrow ``` rust fn doit(s: &String) { println!("s = {}", s); } let x = String::from("hello"); doit(s); println!("x = {}", x); ``` ---- ## Mutable Borrow ``` rust let x = String::from("hello"); let r1 = &mut s; let r2 = &mut s; // Error: cannot borrow `s` as mutable more than once at a time ``` ``` rust let x = String::from("hello"); let r1 = &s; let r2 = &s; let r3 = &mut s; // Error: cannot borrow `s` as mutable because it is also borrowed as immutable ``` --- ## Lifetime Parameters ``` rust fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } // Error: missing lifetime specifier // Help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y` ``` ``` rust fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } ``` --- ## Smart Pointers ``` rust let x = Box::new(5); ``` ``` rust let x = Rc::new(5); ``` --- ## OOP ``` rust struct Foo { i: usize, } impl Foo { fn new(i: usize) -> Self { Self { i } } fn i(&self) -> usize { self.i } fn add(&mut self, i: usize) { self.i += i; } } impl std::fmt::Debug for Foo { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Foo (i={})", self.i) } } ``` --- ## Derive ``` rust #[derive(Debug,Copy,Clone,PartialEq,PartialOrd)] struct Foo { i: usize, } ``` --- ## Macros ``` rust println!("Hello, {}", world); // It's type-safe ``` --- ## Resources * https://www.rust-lang.org/en-US/ * https://doc.rust-lang.org/book/second-edition/ * https://crates.io/
{"slideOptions":{"transition":"fade","theme":"white"}}