Or an appointment from oneself (which, I think, involves building a new thing from it, because in the case of Link(item, *self) , a move is implied. This means that in the process of building a new Link , that itself becomes unusable, because:
"Once the value has been moved, it can no longer be used from its original position and will not be destroyed there."
The Right Way ™ is probably best documented by what is done in this example in stdlib . This is a doubly linked list, and it is managed, but it has been changed, and I hope it will be free. There is also a list of useful container types .
However, I managed to get this immutable version of your data structure.
trait Stack<T> { fn push(self, item : T) -> Self; fn pop(self) -> Option<(T, Self)>; fn new() -> Self; } #[deriving(Eq, ToStr)] enum Chain<T> { Link(T, ~Chain<T>), Break } impl<T> Stack<T> for Chain<T> { fn push(self, item : T) -> Chain<T> { Link(item, ~self) } fn pop(self) -> Option<(T, Chain<T>)> { match self { Link(item, ~new_self) => Some((item, new_self)), Break => None } } fn new() -> Chain<T> { Break } } fn main() { let b : ~Chain<int> = ~Stack::new(); println(b.push(1).push(2).push(3).to_str()); }
tehgeekmeister
source share