Search code examples
arraysrusttuples

How to reinterpret an array of f64 as a tuple of f64 elements?


I have a code generator which produces call to a function that returns Vec<f64>. I need to assign these values into a set of variables, and the best way seems to be a tuple of those variables. Something like this:

let array: &[f64] = &my_function(3);
let (a, b, c): (f64, f64, f64) = unsafe { std::mem::transmute(*array) };

playground (uncompillable)

I did not figure out how to write the unsafe part to have it accepted by the compiler.

I prefer to avoid generating the item per item assignments, because performance is of huge importance here.

Can this be done? Is the memory layout of a tuple compatible with array?


Solution

  • You cannot do this, period; tuples do not have a guaranteed memory layout, therefore you cannot transmute from something that may or may not match.

    I would do normal pattern matching:

    fn main() {
        let values = my_function(3);
        dbg!(&values);
        let (a, b, c) = match &*values {
            [a, b, c] => (a, b, c),
            _ => panic!(),
        };
        dbg!(a, b, c);
    }
    
    fn my_function(count: usize) -> Vec<f64> {
        vec![3.14_0f64; count]
    }
    

    See also: