Can I destructure a tuple without binding the result to a new variable in a let/match/for statement?

前端 未结 2 894
我寻月下人不归
我寻月下人不归 2020-11-27 06:24

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

2条回答
  •  独厮守ぢ
    2020-11-27 07:06

    Nightly Rust has feature(destructuring_assignment), which allows your original attempt to compile as-is:

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

    However, I'd solve this using stable features like slice pattern matching, which avoids the need for the double check in split_at and is_empty:

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

    See also:

    • How to swap two variables?

提交回复
热议问题