Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a boxed array into a Vec in Rust

Tags:

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?

like image 913
fyaa Avatar asked Mar 02 '16 15:03

fyaa


2 Answers

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);
}
like image 176
evilone Avatar answered Sep 21 '22 07:09

evilone


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();
like image 27
Thierry Avatar answered Sep 18 '22 07:09

Thierry