How to move a state owned pointer

For reference, I am using Rust 0.7.

I am trying to create a stack implementation using a linked list and I am having problems.

trait Stack<T> { fn push(&mut self, item : T); fn pop(&mut self) -> Option<T>; } enum Chain<T> { Link(T, ~Chain<T>), Break } impl<T> Stack<T> for ~Chain<T> { fn push(&mut self, item : T) { *self = ~Link(item, *self); } fn pop(&mut self) -> Option<T> { None } } 

When I try rustc stack.rs , I get the following error:

 stack.rs:13:28: 13:34 error: cannot move out of dereference of & pointer stack.rs:13 *self = ~Link(item, *self); ^~~~~~ 

I do not know how I could overcome this or what I could do differently to resolve this. It seems like I would have to create this data structure without using managed pointers, but I have not seen much documentation about this.

+8
rust
source share
1 answer

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()); } 
+5
source share

All Articles