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 typeBox<[_; 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, 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With