Rust
所有权
let x = 5;—Immutable variable
let mut x = 5;—Mutable variable
const MAX: u32 = 100;—Compile-time constant
fn main() { }—Entry point
println!("Hello {}", name)—Print with format
println!("{:?}", val)—Debug print
let x: i32 = 5;—Explicit type annotation
use std::io;—Import module
类型
i8/i16/i32/i64/i128—Signed integers
u8/u16/u32/u64/u128—Unsigned integers
f32 / f64—Floating point
bool—true or false
char—Unicode character
&str—String slice (borrowed)
String—Owned string
(i32, f64)—Tuple
[i32; 5]—Fixed-size array
Vec<T>—Dynamic array
Option<T>—Some(T) or None
Result<T, E>—Ok(T) or Err(E)
结构体与枚举
let s2 = s1;—Move ownership (s1 invalid)
let s2 = s1.clone();—Deep copy (both valid)
&x—Immutable borrow (reference)
&mut x—Mutable borrow
fn f(s: &String)—Borrow in function
fn f(s: &mut String)—Mutable borrow in fn
'a lifetime annotation—Explicit lifetime
'static—Lives entire program
错误处理
struct Point { x: f64, y: f64 }—Named struct
impl Point { fn new() -> Self }—Implement methods
self / &self / &mut self—Method receivers
enum Color { Red, Green, Blue }—Simple enum
enum Msg { Quit, Move {x,y} }—Enum with data
match val { Pat => expr }—Pattern matching
if let Some(x) = opt { }—Conditional unwrap
#[derive(Debug, Clone)]—Auto-derive traits
特征
Result<T, E>—Recoverable error type
Ok(val) / Err(e)—Result variants
.unwrap()—Panic if Err/None
.expect("msg")—Panic with message
?—Propagate error (return Err)
.unwrap_or(default)—Default on error
.map_err(|e| ...)—Transform error
panic!("msg")—Unrecoverable error
Traits
trait MyTrait { fn method(); }—Define trait
impl Trait for Type { }—Implement trait
fn f(x: &dyn Trait)—Dynamic dispatch
fn f(x: impl Trait)—Static dispatch
fn f<T: Trait>(x: T)—Generic with bound
where T: Trait + Clone—Where clause bounds
Box<dyn Trait>—Trait object on heap
Collections
Vec::new() / vec![1,2,3]—Create vector
v.push(x) / v.pop()—Add / remove last
v.iter().map(|x| ...)—Iterator map
v.iter().filter(|x| ...)—Iterator filter
.collect::<Vec<_>>()—Collect into container
HashMap::new()—Create hash map
map.insert(k, v)—Insert key-value
map.get(&k)—Get value (returns Option)
HashSet::new()—Create hash set
.for_each(|x| ...)—Iterate with closure
Control Flow
if cond { } else { }—If expression
let x = if c { a } else { b };—If as expression
loop { break val; }—Infinite loop with return
while cond { }—While loop
for x in iter { }—For-in loop
for i in 0..10 { }—Range loop
match val { _ => {} }—Match (exhaustive)
allprintabledoc.com