The reason your code does not compile is because the unique pointer ~ can only have one owner. The compiler is stopping you from writing error-prone code. You can either decide to return a copy of objects, links to objects, or a piece of objects (this is a link to vector data or its segment).
Copy solution
struct Widget { thingies: ~[int] } impl Widget { fn new() -> Widget { Widget { thingies: ~[4, 8, 15, 16, 23, 42] } } fn somethings(&self) -> ~[int] { self.thingies.clone() } }
Reference Solution
struct Widget { thingies: ~[int] } impl Widget { fn new() -> Widget { Widget { thingies: ~[4, 8, 15, 16, 23, 42] } } fn somethings<'a>(&'a self) -> &'a~[int] { &self.thingies } }
Slice Solution
struct Widget { thingies: ~[int] } impl Widget { fn new() -> Widget { Widget { thingies: ~[4, 8, 15, 16, 23, 42] } } fn somethings<'a>(&'a self) -> &'a[int] { self.thingies.as_slice() } }
In order to understand the solutions of links and slices, you need to understand what 'a means: it indicates the lifetime, and &'a is a way to tell the compiler that the link should never survive the object that it refers to, which in this case is a widget.
These solutions also have some limitations: you cannot change the object that you are currently referencing, because it makes reference reversal impossible.
You can, of course, change thingies if you return a volatile link. Changed link over time will be recorded &'a mut T
struct Widget { thingies: ~[int] } impl Widget { fn new() -> Widget { Widget { thingies: ~[4, 8, 15, 16, 23, 42] } } fn somethings<'a>(&'a mut self) -> &'a mut ~[int] { &mut self.thingies } }
Note I believe that in Rust 0.8 you need to write &'self instead of &'a , because lifetimes with user names have not yet been supported. I also wrote this in 0.9.
Edit: Removed redundant life expectancy ads.