Good way to unpack vector<string>?

Hi.
I'm trying to unpack Vector.

The followings are what I've tried.

  1. using match (but [a,b,c,d] was repeated)
// `vs` is Vector<String>
let [a,b,c,d] = match &vs[..] {
                        [a,b,c,d] => [a,b,c,d],
                        _ => panic!("Error")
                    };
  1. using next repeatedly
let vec_iter = vs.iter()

let a = vec_iter.next().unwrap();
let b = vec_iter.next().unwrap();
...

Could you tell me the good way to do it? It would be good that I can improve repeated [a,b,c,d] in 1 also.

You could also use let-else:

let [a, b, c, d] = &vs.get(this_id).unwrap()[..] else {
    panic!("Error")
};
3 Likes

I'd normally use the TryFrom impl for this:

let [a, b, c, d] = vs.try_into().unwrap();

One of the nice side-effects is that you get the elements by-value (throw in .as_slice() for by-reference) and don't need the [..] syntax, which I've always found a bit ugly.

Often type inference will do the right thing for you, otherwise you'll need to add types yourself (let [a, b, c, d]: [u8: 4] = ...).

5 Likes

This will actually get better in 1.73 as well: https://github.com/rust-lang/rust/pull/113199

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.