一、枚举与模式匹配
Rust 的 enum 可带数据,比 C 的 union 安全;配合 match 穷尽匹配:
enum Msg { Quit, Move { x: i32, y: i32 }, Write(String) }
match m {
Msg::Quit => {},
Msg::Move { x, y } => println!("{} {}", x, y),
Msg::Write(s) => println!("{}", s),
}
二、Option 与 Result(消灭 null)
Option<T>:有值Some(t)或无None,强制处理缺失;Result<T, E>:成功Ok(t)或失败Err(e),替代异常;?运算符快速向上传播错误。
三、Cargo 与 trait
cargo new demo && cd demo
cargo build / cargo run / cargo test
依赖写在 Cargo.toml。trait 类似接口,类型隐式实现即可被泛型约束:
trait Summary { fn title(&self) -> String; }
Rust 用”代数数据类型 + 所有权 + trait”组合出表达力强又安全的抽象,是近年最受热捧的系统语言。