The reason your code doesn't compile is that a unique pointer ~
can have only one owner. The compiler is preventing you from writing error prone code. You can either decide to return a copy of thingies, a reference to thingies, or a slice of thingies (which is a reference to the vector data or a segment of it).
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()
}
}
To understand the reference and slice solutions you need to understand what 'a
means: it indicates a lifetime, and &'a
is a way to tell the compiler that the reference must never outlive the object it references, which in this case is a Widget.
These solutions also have some limitations: you cannot modify an object that you're currently referencing because doing so opens up the possibility of the references becoming invalid.
You can of course modify thingies if you return a mutable reference. A mutable reference with a lifetime would be written &'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 custom names weren't supported yet. I also wrote this in 0.9.
Edit: removed redundant lifetime declarations.