Can I destructure a tuple without binding the resu

2020-01-27 05:58发布

问题:

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?

回答1:

No.

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.

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



标签: rust