我想解构一个元组,将结果的一部分分配给一个新变量,并将结果的另一部分分配给一个现有变量.
下面的代码说明了其意图(这是一个导致无限循环的愚蠢示例):
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
,而不是重新分配它.
如果我将代码更改为以下内容(以避免引入新list
变量的let
),它将无法编译:
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
|
有没有办法做到这一点,或者只能在let
、match
和for
语句中使用解构?