我可以在不将结果绑定到let/match/for语句中的新变量的情况下构造元组吗?

Cor*_*lks 17 rust

我想构造一个元组并将结果的一部分分配给一个新变量,并将结果的另一部分分配给现有的.

以下代码说明了intent(这是一个导致无限循环打印的愚蠢示例[0]):

fn main() {
    let mut list = &[0, 1, 2, 3][..];
    while !list.is_empty() {
        let (head, list) = list.split_at(1);
        // An obvious workaround here is to introduce a new variable in the above
        // let statement, and then just assign it to list.
        println!("{:?}", head);
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码创建一个新变量,list而不是重新分配它.

如果我将代码更改为以下(为了避免let引入新list变量),它不会编译:

fn main() {
    let mut list = &[0, 1, 2, 3][..];
    while !list.is_empty() {
        let head;
        (head, list) = list.split_at(1);
        println!("{:?}", head);
    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

error[E0070]: invalid left-hand side expression
 --> src/main.rs:5:9
  |
5 |         (head, list) = list.split_at(1);
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ left-hand of expression not valid
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,或者可以解构只能在使用let,matchfor语句?

McG*_*ady 21

是的。

Rust 团队于 2022 年 2 月 24 日发布了 Rust 1.59.0 的新版本,您现在可以使用元组、切片和结构模式作为作业的左侧。

宣布 Rust 1.59.0

解构作业

您现在可以使用元组、切片和结构模式作为赋值的左侧。

let (a, b, c, d, e);

(a, b) = (1, 2); [c, .., d, _] = [1, 2, 3, 4, 5]; Struct { e, .. } =
Struct { e: 5, f: 3 };

assert_eq!([1, 2, 1, 4, 5], [a, b, c, d, e]);
Run Code Online (Sandbox Code Playgroud)

这使得赋值与 let 绑定更加一致,它们长期以来都支持相同的事情。请注意,不允许使用 += 等运算符进行解构赋值。

在 1.59.0 之前,您只能在 Nightly 版本中使用#![feature(destructuring_assignment)].

现在你可以在稳定版本中执行此技巧并删除功能线。

请参阅rust-lang/rust/issues/71126rust-lang/rust/pull/90521的更多详细信息。


DK.*_*DK. 16

没有.

解构是你只能用模式做的事情; 赋值的左侧不是模式,因此您无法进行destructure-and-assign.

请参阅proto-RFC 372(解构分配),其中讨论了添加此功能的可能性.

  • 从 Rustc 1.59.0 开始添加 (5认同)