Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

translation(appendix/rust-versions) : 1.83 #1484

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,3 +389,4 @@
- [1.80](appendix/rust-versions/1.80.md)
- [1.81](appendix/rust-versions/1.81.md)
- [1.82](appendix/rust-versions/1.82.md)
- [1.83](appendix/rust-versions/1.83.md)
82 changes: 82 additions & 0 deletions src/appendix/rust-versions/1.83.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Rust 新版解读 | 1.83 | Const 能力拓展

> Rust 1.83 官方 release doc: [Announcing Rust 1.83.0 | Rust Blog](https://blog.rust-lang.org/2024/11/28/Rust-1.83.0.html)

通过 [rustup](https://www.rust-lang.org/tools/install) 安装的同学可以使用以下命令升级到 1.83 版本:

```shell
$ rustup update stable
```

## 新的常量能力

此版本包含了对 `const` 上下文中运行的代码的几个重大扩展。这指的是编译器必须在编译时求值的代码:包括 `const` 和 `static` 项的初始值、数组长度、枚举判别值、`const` 泛型参数,以及可从这些上下文中调用的函数(`const fn`)。

**对静态值的引用。** 此前,除了 `static` 项的初始化表达式外,`const` 上下文中不能引用 `static` 项。这一限制现已解除:

```rust
static S: i32 = 25;
const C: &i32 = &S;
```

然而,在 `const` 上下文中仍然不允许读取可变或内部可变静态项的值。此外,常量的最终值不能引用任何可变或内部可变静态项:

```rust
static mut S: i32 = 0;

const C1: i32 = unsafe { S };
// error: constant accesses mutable global memory

const C2: &i32 = unsafe { &S };
// error: encountered reference to mutable memory in `const`
```

这些限制确保了常量仍然是“常量”:它们求值后的值,及其作为模式的意义(可能涉及解引用引用)在整个程序执行过程中将保持不变。

也就是说,常量允许是指向可变或内部可变静态变量的原始指针:

```rust
static mut S: i32 = 64;
const C: *mut i32 = &raw mut S;
```

**可变引用和指针。** 现在可以在 `const` 上下文中使用可变引用:

```rust
const fn inc(x: &mut i32) {
*x += 1;
}

const C: i32 = {
let mut c = 41;
inc(&mut c);
c
};
```

可变原始指针和内部可变性也得到了支持:

```rust
use std::cell::UnsafeCell;

const C: i32 = {
let c = UnsafeCell::new(41);
unsafe { *c.get() += 1 };
c.into_inner()
};
```

然而,可变引用和指针只能在常量的计算过程中使用,不能成为常量最终值的一部分:

```rust
const C: &mut i32 = &mut 4;
// error[E0764]: mutable references are not allowed in the final value of constants
```

此版本还带来了一批新的函数,这些函数现在在 `const` 上下文中是稳定的(参见原文连接里的“稳定的API”部分的末尾)。

这些新能力和稳定的API解锁了在 `const` 上下文中执行的全新代码类别,我们很高兴看到Rust生态系统将如何利用这一点!

## Others

其它更新细节,和稳定的 API 列表,参考[原Blog](https://blog.rust-lang.org/2024/11/28/Rust-1.83.0.html#stabilized-apis)