Merge pull request #1430 from EluvK/eluvk/translation/appendix/rust-versions

translation(appendix/rust-versions) : 1.79
pull/1304/merge
Sunface 3 months ago committed by GitHub
commit d6dd113070
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -385,3 +385,4 @@
- [1.76](appendix/rust-versions/1.76.md) - [1.76](appendix/rust-versions/1.76.md)
- [1.77](appendix/rust-versions/1.77.md) - [1.77](appendix/rust-versions/1.77.md)
- [1.78](appendix/rust-versions/1.78.md) - [1.78](appendix/rust-versions/1.78.md)
- [1.79](appendix/rust-versions/1.79.md)

@ -0,0 +1,82 @@
# Rust 新版解读 | 1.79 | 内联 const临时变量生命周期延长
> Rust 1.79 官方 release doc: [Announcing Rust 1.79.0 | Rust Blog](https://blog.rust-lang.org/2024/06/13/Rust-1.79.0.html)
通过 [rustup](https://www.rust-lang.org/tools/install) 安装的同学可以使用以下命令升级到 1.79 版本:
```shell
$ rustup update stable
```
## 内联 `const` 表达式
如今可以写内联 const 块 `const {...}` 作为表达式,显式地进入 const 上下文,而不需要额外的声明(例如,定义 `const` 常量或 Trait 的关联常量)。
与 const 常量 `const ITEM: ... = ...` 不同,内联 const 里类型可以被推断而不需要显式写出,并且还能使用泛型参数。来看一个很实用的例子:
```rust
const EMPTY: Option<Vec<u8>> = None;
let foo = [EMPTY; 100];
```
如今可以写成如下形式foo 的类型 `Option<T>` 可以不标注,可以根据上下文推断出来)
```rust
let foo = [const { None }; 100];
```
泛型的例子:
```rust
fn create_none_array<T, const N: usize>() -> [Option<T>; N] {
[const { None }; N]
}
```
更多细节见[参考文档](https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html#const-blocks)
## 关联类型约束
Rust 1.79 稳定了一些关联类型约束的语法,允许我们在类型约束里写其它类型约束,即 `T: Trait<Assoc: Bounds...>`。这避免了提供额外的显式泛型类型来约束关联类型。
这个新特性允许我们在一些情况下更简单地指定好约束关系,解决了一些之前不可能或者会引入额外不必要约束的场景。
- **`where` 子句** - 在这个位置,这等同于将约束拆分为两个(或更多)`where` 语句。例如,`where T: Trait<Assoc: Bound>` 等同于 `where T: Trait, <T as Trait>::Assoc: Bound`
- **Supertraits** - 类似于上面,`trait CopyIterator: Iterator<Item: Copy> {}`。这也等同于将约束拆分为两个(或更多)`where` 语句;不过当 trait 被使用时,这个对关联类型 Item 的约束是隐含的。
- **关联类型 Item 约束** - 允许约束与 trait 的关联类型相关的嵌套类型约束。例如 `trait Trait { type Assoc: Trait2<Assoc2: Copy>; }`
- **模糊类型约束**RPIT: return position `impl Trait`, TAIT: type alias `impl Trait` - 允许约束与模糊类型相关的关联类型。例如 `impl Iterator<Item: Copy>` 定义了 Item 满足 Copy 的迭代器,而不必实际命名该约束。
更多细节见 [issue](https://github.com/rust-lang/rust/pull/122055/#issue-2170532454)
译注:很绕,但是整体上就是一次让 Rust 编译器变得更符合你期望它应该正常工作的样子的更新。
## 临时变量生命周期延长
现在,在 `match``if` 结构中构造并立刻被使用的临时变量的生命周期会自动延长。这与代码结构中的临时变量生命周期延长的效果一致。
```rust
let a = if true {
..;
&temp() // used to error, but now gets lifetime extended
} else {
..;
&temp() // used to error, but now gets lifetime extended
};
let a = match () {
_ => {
..;
&temp() // used to error, but now gets lifetime extended
}
};
// 之前已有的代码块临时变量生命周期延长
let a = {
..;
&temp() // lifetime is extended
};
```
## Others
其它更新细节,和稳定的 API 列表,参考[原Blog](https://blog.rust-lang.org/2024/06/13/Rust-1.79.0.html#stabilized-apis)
Loading…
Cancel
Save