我可以在不将结果绑定到 let/match/for 语句中的新变量的情况下解构元组吗? [英] Can I destructure a tuple without binding the result to a new variable in a let/match/for statement?

查看:40
本文介绍了我可以在不将结果绑定到 let/match/for 语句中的新变量的情况下解构元组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to destructure a tuple and assign part of the result to a new variable and assign another part of the result to an existing.

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

The following code illustrates the intent (it's a dumb example which results in an infinite loop printing [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);
    }
}

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

This code creates a new variable list instead of reassigning it.

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

If I change the code to the following (to avoid the let that introduces the new list variable), it doesn't compile:

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

编译错误:

error[E0070]: invalid left-hand side of assignment
 --> src/main.rs:5:22
  |
5 |         (head, list) = list.split_at(1);
  |         ------------ ^
  |         |
  |         cannot assign to this expression
  |

有没有办法做到这一点,或者只能在letmatchfor语句中使用解构?

Is there a way to do this, or can destructuring only be used in let, match, and for statements?

推荐答案

没有

解构是你只能用模式做的事情;赋值的左侧不是一个模式,因此你不能解构和赋值.

Destructuring is something you can only do with patterns; the left-hand side of an assignment is not a pattern, hence you can't destructure-and-assign.

参见 proto-RFC 372(解构赋值),其中讨论了添加此功能.

See proto-RFC 372 (Destructuring assignment) which discusses the possibility of adding this feature.

这篇关于我可以在不将结果绑定到 let/match/for 语句中的新变量的情况下解构元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆