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.
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);
}
}
This code creates a new variable list
instead of reassigning it.
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);
}
}
Compilation error:
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
Is there a way to do this, or can destructuring only be used in let
, match
, and for
statements?