Supreet Singh
Supreet Singh

Reputation: 127

How to destructure a vector efficiently

I am trying to find an efficient way to destructure the vector in rust. Assigning the values on the index to the respective variable. I have been through the documentations and was not able to find the answer.

let (frequency, samplingrate, samples, slope, duration, steps) = (input[0], input[1], input[2], input[3], input[4], input[5]);

Upvotes: 1

Views: 141

Answers (1)

PitaJ
PitaJ

Reputation: 15012

The Rust name for this is Slice patterns.

But slice patterns can not be used irrefutably, except with an array. That is, you can't just do something like this:

let [a, b, c] = v[..3];

Because the compiler can't prove that the resulting slice is 3 elements long, even though it may be obvious to us.

Instead, you need to tell the compiler to convert the given slice into an array instead, like so:

let [a, b, c]: &[_; 3] = v[..3].try_into().unwrap();

Because array sizes are known at compile time, the compiler can prove that such an operation is infallible.

Here's what the code should look like for your case:

let [frequency, samplingrate, samples, slope, duration, steps]: &[_; 6] = input[..6].try_into().unwrap();

playground

Upvotes: 11

Related Questions