News for hackers. Stuff that matters.
Re:A year with Go by webkike on Friday June 05, 2015 @07:05PM (#9668741)
That's fantastic to know. I might just switch back to rust because of this.
Re:A year with Go by masklinn on Saturday June 06, 2015 @04:24AM (#9670134)
If you have known lifetimes, you can also use &Trait (and lifetime variants thereof): http://is.gd/4SyShN

For more information on that, check out "trait objects" (http://doc.rust-lang.org/book/trait-objects.html).

The gist of the issue is this: a Vec (and most other collections) needs all items to be sized and of the same size in-memory to lay itself out (know how much memory to reserve for each item for instance), and it stores its stuff inline. So a Vec<u8>'s buffer looks like this:

    [u8|u8|u8|u8]
and a Vec for a struct { u8, u32, u8 } looks like this (ignoring padding):

    [u8,u32,u8|u8,u32,u8|u8,u32,u8|u8,u32,u8]
If you want to store both A and B inline in a Vec you've got trouble: that they both implement Foo doesn't mean they have the same size at all (and they often don't), and Rust's type system doesn't allow it anyway (`A: Foo` says that A implements Foo, but the function or collection still gets an A via reification and monomorphisation).

The alternative is to do what languages Java or Go do under the covers: add a fixed-size pointer as indirection between the collection and the actual items (the pointer is actually fat, you get a pointer to the instance itself and a pointer to the vtable for the trait implementation, I think Go does the same but java doesn't as each instance has its classpointer), so you get e.g.

    [&A|&A|&B|&A]
all pointers are the same size and things work out. More generally than trait objects, you need to do this to store any unsized type (http://doc.rust-lang.org/book/unsized-types.html) in something which only accepts sized types.