I'm trying to write a binary searching tree in Rust, but I don't understand what is going on:
enum BST<'a, T: Ord> {
Leaf,
BinTree { value: T, left: &'a mut BST<'a, T>, right: &'a mut BST<'a, T> }
}
impl<'a, T: Ord> BST<'a, T> {
fn new() -> BST<'a, T> {
BST::Leaf
}
fn add(self, val: T) {
match self {
BST::Leaf => self = BST::BinTree {
value: val,
left: &mut BST::<'a, T>::new(),
right: &mut BST::<'a, T>::new()
},
BST::BinTree{value: v, left: l, right: r} => if val < v {
l.add(val);
} else {
r.add(val);
}
}
}
}
fn main() {
}
When I try to compile this, I get the following errors:
error[E0309]: the parameter type `T` may not live long enough
--> heap.rs:3:25
|
3 | BinTree { value: T, left: &'a mut BST<'a, T>, right: &'a mut BST<'a, T> }
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a mut BST<'a, T>` does not outlive the data it points at
--> heap.rs:3:25
|
3 | BinTree { value: T, left: &'a mut BST<'a, T>, right: &'a mut BST<'a, T> }
| ^^^^^^^^^^^^^^^^^^^^^^^^
Well, after doing lots of research and doing the things that the compiler suggests I came up with this code:
enum BST<'a, T: Ord + 'a> {
Leaf,
BinTree {
value: T,
left: &'a mut BST<'a, T>,
right: &'a mut BST<'a, T>
}
}
impl<'a, T: Ord + 'a > BST<'a, T> {
fn new() -> BST<'a, T> {
BST::Leaf
}
fn add(&mut self, val: T) {
match *self {
BST::Leaf => *self = BST::BinTree {
value: val,
left: &mut BST::<'a, T>::new() as &'a mut BST<'a, T>,
right: &mut BST::<'a, T>::new() as &'a mut BST<'a, T>
},
BST::BinTree{value: ref v, left: ref mut l, right: ref mut r} => if val < *v {
l.add(val);
} else {
r.add(val);
}
}
}
}
fn main() {
}
But I still get errors:
error: borrowed value does not live long enough
--> heap.rs:19:16
|
19 | left: &mut BST::<'a, T>::new() as &'a mut BST<'a, T>,
| ^^^^^^^^^^^^^^^^^^^ does not live long enough
20 | right: &mut BST::<'a, T>::new() as &'a mut BST<'a, T>
21 | },
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 15:27...
--> heap.rs:15:28
|
15 | fn add(&mut self, val: T) {
| ____________________________^
16 | | match *self {
17 | | BST::Leaf => *self = BST::BinTree {
18 | | value: val,
... |
27 | | }
28 | | }
| |__^
error: borrowed value does not live long enough
--> heap.rs:20:17
|
20 | right: &mut BST::<'a, T>::new() as &'a mut BST<'a, T>
| ^^^^^^^^^^^^^^^^^^^ does not live long enough
21 | },
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 15:27...
--> heap.rs:15:28
|
15 | fn add(&mut self, val: T) {
| ____________________________^
16 | | match *self {
17 | | BST::Leaf => *self = BST::BinTree {
18 | | value: val,
... |
27 | | }
28 | | }
| |__^
error: aborting due to 2 previous errors
I know this can be fixed by using Box
es instead of references, but I want to make it like this for exercise.