fyaa
fyaa

Reputation: 676

How to convert a boxed array into a Vec in Rust

I have a boxed array of structs and I want to consume this array and insert it into a vector.

My current approach would be to convert the array into a vector, but the corresponding library function does not seem to work the way I expected.

let foo = Box::new([1, 2, 3, 4]);
let bar = foo.into_vec();

The compiler error states

no method named into_vec found for type Box<[_; 4]> in the current scope

I've found specifications here that look like

fn into_vec(self: Box<[T]>) -> Vec<T>
Converts self into a vector without clones or allocation.

... but I am not quite sure how to apply it. Any suggestions?

Upvotes: 12

Views: 6003

Answers (2)

evilone
evilone

Reputation: 22750

I think there's more cleaner way to do it. When you initialize foo, add type to it. Playground

fn main() {
    let foo: Box<[u32]> = Box::new([1, 2, 3, 4]);
    let bar = foo.into_vec();

    println!("{:?}", bar);
}

Upvotes: 12

Thierry
Thierry

Reputation: 1139

The documentation you link to is for slices, i.e., [T], while what you have is an array of length 4: [T; 4].

You can, however, simply convert those, since an array of length 4 kinda is a slice. This works:

let foo = Box::new([1, 2, 3, 4]);
let bar = (foo as Box<[_]>).into_vec();

Upvotes: 9

Related Questions