Ultimate Rust Crash Course !!top!! Info
let x = 5; let x = x + 1; // shadows previous x { let x = x * 2; println!("Inner: {}", x); // 12 } println!("Outer: {}", x); // 6 Shadowing lets you change type without renaming:
| Concept | Syntax / Rule | |---------|----------------| | Immutable var | let x = 5; | | Mutable var | let mut x = 5; | | Function | fn add(a: i32, b: i32) -> i32 a + b | | Ownership move | let s2 = s1; (s1 invalid) | | Borrow reference | fn calc(&s: &String) | | Mutable borrow | &mut – only one at a time | | Option | match option Some(x) => ..., None => ... | | Error handling | result? inside Result -returning fn | | Lifetime | <'a> ties lifetimes of references | ultimate rust crash course
cargo new hello_rust cd hello_rust cargo run Inside src/main.rs : let x = 5; let x = x
let some_number = Some(5); let absent_number: Option<i32> = None; // You cannot add Option<i32> to i32 directly. let x: i32 = 5; let y: Option<i32> = Some(10); // let sum = x + y; // ERROR: mismatched types let x: i32 = 5; let y: Option<i32>
impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {}", self.headline, self.location) } }
'a means “the returned reference lives at least as long as both inputs.”
let mut s = String::from("hello"); let r1 = &s; // immutable borrow let r2 = &s; // another immutable borrow // let r3 = &mut s; // ERROR: cannot borrow as mutable Slices let you reference part of a collection without copying.