18
Rust 2024 edition 新特性
Rust 2024 Edition
2024 edition 于 2024 年 Q4 随 Rust 1.85 稳定。要用它,得在 Cargo.toml 写 edition = "2024"。老项目迁移跑一句 cargo fix --edition 就行。
| 特性 | 一句话说明 |
|---|---|
| let-else | 模式匹配失败就提前返回,少写一堆 match { Ok(v)=>v, _=>return } |
| if-let chains | if let Some(a)=x && let Some(b)=y { ... },连写不再嵌套 |
| async fn in trait | trait 里能直接写 async fn,异步 trait 终于不别扭了 |
| unsafe extern blocks | 默认 C ABI,FFI 更安全 |
| RPITIT | trait 方法返回 impl Trait,API 设计更灵活 |
| gen blocks(生成器) | gen 块能 yield 逐个产出值,写迭代器不用自己实现 Iterator trait(以官网最新稳定版为准,仍在推进) |
// let-else:匹配成功就绑定,失败直接 return/break
fn first_char(s: &str) -> Option<char> {
let Some(c) = s.chars().next() else { return None; };
Some(c)
}
fn main() {
println!("{:?}", first_char("hello")); // Some('h')
}
$ cargo run
Some('h')