Rust团队刚刚发布了Rust 1.80.0,我们来看看有哪些新特性。
LazyCell和LazyLock
这两个新类型将数据初始化延迟到第一次访问。LazyLock是线程安全的,适合静态值,而LazyCell不是线程安全的,但可以用于线程局部静态。
使用LazyLock的例子:
use std::sync::LazyLock;
use std::time::Instant;
static LAZY_TIME: LazyLock<Instant> = LazyLock::new(Instant::now);
// 堆代码 duidaima.com
fn main() {
let start = Instant::now();
std::thread::scope(|s| {
s.spawn(|| {
println!("Thread lazy time is {:?}", LAZY_TIME.duration_since(start));
});
println!("Main lazy time is {:?}", LAZY_TIME.duration_since(start));
});
}
检查cfg名称和值
Cargo 1.80现在包含了对cfg名称和值的检查,以捕获拼写错误和错误配置,从而提高了条件配置的可靠性。
cfg检查示例:
fn main() {
println!("Hello, world!");
#[cfg(feature = "crayon")]
rayon::join(
|| println!("Hello, Thing One!"),
|| println!("Hello, Thing Two!"),
);
}
运行结果:
warning: unexpected `cfg` condition value: `crayon`
--> src/main.rs:4:11
|
4 | #[cfg(feature = "crayon")]
| ^^^^^^^^^^--------
| |
| help: there is an expected value with a similar name: `"rayon"`
|
= note: expected values for `feature` are: `rayon`
= help: consider adding `crayon` as a feature in `Cargo.toml`
模式匹配中的专属范围
Rust现在支持专属范围的模式匹配(a..b),这增强了模式匹配并减少了对包含端点的单独常量的需求。
使用专属范围的示例:
pub fn size_prefix(n: u32) -> &'static str {
const K: u32 = 10u32.pow(3);
const M: u32 = 10u32.pow(6);
const G: u32 = 10u32.pow(9);
match n {
..K => "",
K..M => "k",
M..G => "M",
G.. => "G",
}
}