Selva
Selva

Reputation: 1153

Convert Vec<[f64;1]> to Vec<f64>

I am new to rust and I am playing with it. When I was following some tutorial, I found a vector of type <[f64,1]>. I thought it should be simple to transform it to [f64] but could not find a simple way other than for loop. Is there other way?

let y: Vec<[f64;1]> = [[1],[2],[3],[4]];
let mut y2: Vec<f64> = Vec::new();
    for each in &y {
        y2.push(each[0]);
}

Upvotes: 1

Views: 1114

Answers (2)

elsuizo
elsuizo

Reputation: 154

you could use the flatten() method:

let y_vec: Vec<f64> = y.iter().flatten().cloned().collect();

Upvotes: 0

SOFe
SOFe

Reputation: 8214

y in your example is not a Vec; you probably forgot vec! in front. Furthermore, floats should be 1.0 not 1.

I don't know why you find this for loop not simple, but if you want other ways:

Using iterator pattern

let y: Vec<[f64; 1]> = vec![[1.0], [2.0], [3.0], [4.0]];
let y2: Vec<f64> = y.iter().map(|&[f]| f).collect();

Using unsafe

Since [f64; 1] and f64 are equal-sized (both 8 bytes), we can transmute the Vec directly:

let y: Vec<[f64; 1]> = vec![[1.0], [2.0], [3.0], [4.0]];
let y2 = unsafe {
    // Ensure the original vector is not dropped.
    let mut y = std::mem::ManuallyDrop::new(y);
    Vec::from_raw_parts(y.as_mut_ptr() as *mut f64,
                        y.len(),
                        y.capacity())
};

This is more complex, but it will reuse the same memory without copying.

Upvotes: 2

Related Questions