Skip to content

Instantly share code, notes, and snippets.

@nikomatsakis
Created September 3, 2013 18:33
Show Gist options
  • Save nikomatsakis/6427775 to your computer and use it in GitHub Desktop.
Save nikomatsakis/6427775 to your computer and use it in GitHub Desktop.
// how can we do a tree in Rust, where each node
// tells its children to update, and in turn, the
// child may update the parent?
//
// The following example doesn't compile in 2 places.
struct TreeData {
last: int
}
struct Tree<'self> {
children: ~[~Tree<'self>],
func: &'self fn(&mut TreeData, int) -> int,
data: TreeData
}
impl<'self> Tree<'self> {
fn update_children(&mut self, val: int) -> int {
for s in self.children.mut_iter() {
(s.func)(&mut self.data, 7);
}
return 5;
}
}
fn square(parent : &mut TreeData, x: int) -> int {
let res = x * x;
parent.last = res;
res
}
fn cube(parent : &mut TreeData, x: int) -> int {
let res = x * x * x;
parent.last = res;
res
}
fn main() {
let child = ~Tree {
children: ~[],
func: square,
data: TreeData {last: 0},
};
let mut parent = ~Tree {
children: ~[child],
func: square,
data: TreeData {last: 0},
};
// error: cannot borrow immutable dereference of ~ pointer as mutable
let cv = parent.update_children(3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment