17611538698
webmaster@21cto.com

Rust 1.80 的新特性

编程语言 0 416 2024-07-26 11:30:25

图片

导读:Rust 1.8的新 LazyCell 和 LazyLock 类型可将其数据的初始化延迟到首次访问时。其范围模式也在语言中最新更新,这受到了不少开发者的关注。

序言


当红并流行的内存安全编程语言Rust 1.80 现在已经正式发布,刚刚它具有“惰性”类型,可以延迟数据初始化直到被第一次访问。


根据 21CTO 综合各方之确切消息,Rust 1.80于当时时间 7 月 25 日正式发布:


图片

https://blog.rust-lang.org/2024/07/25/Rust-1.80.0.html

Rust 1.80.0 关键更新?

1)LazyCell 和 LazyLock

LazyCell 与LazyLock新类型将数据初始化延迟到第一次访问。

其中LazyLock是线程安全的,适用于静态值,而LazyCell不是线程安全的,但可以在线程本地静态中使用。

以下是使用LazyLock的代码示例:

use std::sync::LazyLock;use std::time::Instant;static LAZY_TIME: LazyLock = LazyLock::new(Instant::now);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 1.8 现在支持独占范围模式(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",    }}


更稳定的 API

Rust 1.8 新的稳定 API 包括 Rc 和 Arc 类型的实现,以及Duration、Option、Seek、BinaryHeap、NonNull 等的功能增强。

结语

如何更新到 1.8呢?已通过安装 Rust 旧版本的开发者,可以通过 rustup 的运行更新至最新 1.80 版本。

$ rustup update stable

作者:万能的大雄

评论