1

If I have a slice of structs &[Foo], and I've defined a newtype for Foo called NewFoo, is there a zero-cost way to convert &[Foo] to &[NewFoo]?

The best I've come up with is, which isn't zero-cost:

let _ = foos.iter().map(|foo| NewFoo(*foo)).collect::<Vec<NewFoo>>();
w.brian
  • 16,296
  • 14
  • 69
  • 118
  • [This](https://stackoverflow.com/questions/48308759/how-do-i-convert-a-vect-to-a-vecu-without-copying-the-vector/48309116#48309116) might be of interest. – Michail Mar 09 '19 at 20:31
  • 1
    Rust does not guarantee that a newtype has the same memory layout as the original type. If you are using a `struct` for the newtype, you can use `#[repr(transparent)]` to get this guarantee. – Sven Marnach Mar 09 '19 at 20:48
  • I've added an answer to the question Michail linked above, and I voted to close this one as a duplicate. – Sven Marnach Mar 09 '19 at 21:15
  • Relevant: [`slice::from_raw_parts`](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html) – trent Mar 09 '19 at 21:21

0 Answers0