简体   繁体   中英

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]> 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?

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);
}

The documentation you link to is for slices, ie, [T] , while what you have is an array of length 4: [T; 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM