Destructuring without let

#1

I have a piece of code ( a music decoder ) that returns a tuple with values for the left and the right channel. At the moment the code does the following

let (left,right) = next_sample();
sample[0] = left;
sample[1] = right;

but it feels like I should be able to do something along the lines of

(sample[0],sample[1]) = next_sample();

Is there a way to achieve this or is this just not supported in Rust (yet)

0 Likes

#2
trait Set<T,Index,U> {
    fn set(&mut self, tindex: Index, t: U);
}

impl<T> Set<T,(usize,usize),(T,T)> for [T] {
    fn set(&mut self, tindex: (usize, usize), t: (T,T)) {
        self[tindex.0] = t.0;
        self[tindex.1] = t.1;
    }
}

fn next_sample() -> (i32,i32) {
    return (1,2);
}

fn main() {
    let mut sample: [i32;4] = [0,0,0,0];
    sample.set((0,1),next_sample());
    println!("{:?}",sample);
}
0 Likes

#3

It is not supported.

1 Like

#4

If you change next_sample to return a [T; 2] instead of a tuple, you can do sample.copy_from_slice(&next_sample()) if sample is a type that derefs to a slice and T is Copy. Or use swap_with_slice in a similar manner if it’s not Copy. Just an option to consider …

1 Like

#5
0 Likes