Rust 1.66.0 发布

软件资讯 软件资讯 发布于 2年前 66 浏览 0 回复

Rust 团队于近日发布了 Rust 1.66.0 新版本,1.66.0 稳定版中的主要更新内容如下:

对有字段的枚举进行显式判别

有整数表示的枚举现在可以使用显式判别,即使它们有字段。

#[repr(u8)]
enum Foo {
    A(u8),
    B(i8),
    C(bool) = 42,
}

以前,你可以在有表示的枚举上使用显式判别,但是只有在它们的变体都没有字段的情况下。当跨越语言边界传递值时,显式判别很有用,因为枚举的表示需要在两种语言中匹配。

core::hint::black_box

在对编译器产生的机器代码进行基准测试或检查时,防止优化在某些地方发生往往是有用的。在下面的例子中,函数 push_cap 在一个循环中执行了 Vec::push 4 次。

fn push_cap(v: &mut Vec) {
    for i in 0..4 {
        v.push(i);
    }
}

pub fn bench_push() -> Duration {
    let mut v = Vec::with_capacity(4);
    let now = Instant::now();
    push_cap(&mut v);
    now.elapsed()
}

如果你检查 x86_64 上编译器的优化输出,你会发现它看起来相当短。

example::bench_push:
  sub rsp, 24
  call qword ptr [rip + std::time::Instant::now@GOTPCREL]
  lea rdi, [rsp + 8]
  mov qword ptr [rsp + 8], rax
  mov dword ptr [rsp + 16], edx
  call qword ptr [rip + std::time::Instant::elapsed@GOTPCREL]
  add rsp, 24
  ret

事实上,我们想做基准测试的整个函数 push_cap 已经被优化掉了!

我们可以使用新稳定的 black_box 函数来解决这个问题。从功能上看, black_box 它接受你传递给它的值,并将其直接传回。然而,在内部,编译器将 black_box 视为一个可以对其输入做任何事情并返回任何值的函数。

这对于禁用像我们上面看到的那种优化非常有用。

use std::hint::black_box;

fn push_cap(v: &mut Vec) {
    for i in 0..4 {
        v.push(i);
        black_box(v.as_ptr());
    }
}

cargo remove

Rust 1.62.0 中,我们引入了 cargo add,这是一个在项目中添加依赖项的命令行工具。现在你可以使用 cargo remove 来删除依赖关系。

稳定的 API

  • [proc_macro::Span::source_text]()
  • [u*::{checked_add_signed, overflowing_add_signed, saturating_add_signed, wrapping_add_signed}]()
  • [i*::{checked_add_unsigned, overflowing_add_unsigned, saturating_add_unsigned, wrapping_add_unsigned}]()
  • [i*::{checked_sub_unsigned, overflowing_sub_unsigned, saturating_sub_unsigned, wrapping_sub_unsigned}]()
  • [BTreeSet::{first, last, pop_first, pop_last}]()
  • [BTreeMap::{first_key_value, last_key_value, first_entry, last_entry, pop_first, pop_last}]()
  • [impl TryFrom> for Box<[T; N]>]()
  • [core::hint::black_box]()
  • [Duration::try_from_secs_{f32,f64}]()
  • [Option::unzip]()
  • [std::os::fd]()

其他变化

在 Rust 1.66 版本中还有其他变化,包括

  • 你现在可以在模式中使用 ..=X 范围。
  • Linux 版现在分别用 LTO 和 BOLT 优化了 rustc 前端和 LLVM 后端,提高了运行时性能和内存使用量。

更多详情可查看:https://blog.rust-lang.org/2022/12/15/Rust-1.66.0.html



为您推荐相关文章:

  • Rust 1.80.0 发布
  • Rust 1.70.0 正式发布
  • Rust 1.71.0 稳定版发布
  • Rust 1.72.0 发布,未来支持版本最低为 Windows 10
  • Rust 1.77.0 发布
  • 同类文章推荐:

  • Apache bRPC 1.11.0 发布
  • VirtualBox 7.1.4 发布
  • Python 3.14.0 Alpha 1 发布
  • Elasticsearch 8.15.3 发布
  • Spring Data 2024.1.0 RC1 发布
  • DBeaver 24.2.3 发布