9

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
fyaa
  • 646
  • 1
  • 7
  • 25

2 Answers2

9

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);
}
evilone
  • 22,410
  • 7
  • 80
  • 107
  • So it is better that you are loosing the length information? – fyaa Mar 04 '16 at 08:53
  • @fyaa I think there's no need for length information in your example when you allocating your slice. You are not losing anything. This is not a fixed-size array, but a slice. – evilone Mar 04 '16 at 11:02
  • The length of the slice is encoded into the pointer to the slice (see https://stackoverflow.com/questions/57754901/what-is-a-fat-pointer). No information is being lost. – U007D Nov 25 '22 at 15:19
8

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();
Thierry
  • 1,099
  • 9
  • 19
  • It is strange that a method for a completely different self type `Box<[T]>` can be defined in an `impl Vec`. Is that documented somewhere? https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_vec – starblue Mar 02 '16 at 16:26
  • @starblue As far as I see, the method used here is this one: http://doc.rust-lang.org/std/primitive.slice.html#method.into_vec – Thierry Mar 02 '16 at 16:32
  • @Thierry Maybe, then `Box` is added to `Self` like a reference. The one on `Vec` is still strange. – starblue Mar 02 '16 at 16:48