I'm currently learning Rust and I'm struggling with something I cannot manage to understand.
Consider the following code:
use std::cmp::{Ordering, Ord};
pub enum Error {
ItemAlreadyExists,
}
pub trait BinaryTree<T: Ord> {
fn insert(&mut self, value: T) -> Result<(), Error>;
}
pub struct TreeNode<T> {
data: T,
left: Option<Box<BinaryTree<T>>>,
right: Option<Box<BinaryTree<T>>>,
}
impl<T> TreeNode<T> {
pub fn new(data: T) -> Self {
TreeNode {
data,
left: None,
right: None,
}
}
}
impl<T: Ord> BinaryTree<T> for TreeNode<T> {
fn insert(&mut self, value: T) -> Result<(), Error> {
match value.cmp(&self.data) {
Ordering::Less => match self.left.as_mut() {
Some(left) => left.insert(value),
None => Ok({ self.left = Some(Box::new(TreeNode::new(value))) }),
},
Ordering::Greater => match self.right.as_mut() {
Some(right) => right.insert(value),
None => Ok({ self.right= Some(Box::new(TreeNode::new(value))) }),
},
Ordering::Equal => Err(Error::ItemAlreadyExists),
}
}
}
This is a basic implementation of inserting a value in a binary tree.
The error I'm getting is the following:
error[E0310]: the parameter type `T` may not live long enough
--> src\main.rs:35:47
|
30 | impl<T: Ord> BinaryTree<T> for TreeNode<T> {
| -- help: consider adding an explicit lifetime bound `T: 'static`...
...
35 | None => Ok({ self.left = Some(Box::new(TreeNode::new(value))) }),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What does it mean by parameter T
might not live enough? As far as I know, I'm moving T
around, I'm not borrowing anything so I shouldn't worry about lifetimes, as everything's owned.
What am I missing here?