I am writing a basic binary tree structure and I want to display a node. It seems that Rust has trouble displaying a generic type, and I get this error:
error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--> src/main.rs:55:60
|
55 | write!(f, "Node data: {} left: {:?}, right: {:?}", self.data, self.left, self.right);
| ^^^^^^^^^ trait `T: std::fmt::Display` not satisfied
|
= help: consider adding a `where T: std::fmt::Display` bound
= note: required by `std::fmt::Display::fmt`
error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--> src/main.rs:62:60
|
62 | write!(f, "Node data: {} left: {:?}, right: {:?}", self.data, self.left, self.right);
| ^^^^^^^^^ trait `T: std::fmt::Display` not satisfied
|
= help: consider adding a `where T: std::fmt::Display` bound
= note: required by `std::fmt::Display::fmt`
Here's the full code, including the iterators
struct Node<T> {
data: T,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>,
}
struct NodeIterator<T> {
nodes: Vec<Node<T>>,
}
struct Tree<T> {
root: Option<Node<T>>,
}
impl<T> Node<T> {
pub fn new(value: Option<T>,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>)
-> Node<T> {
Node {
data: value.unwrap(),
left: left,
right: right,
}
}
pub fn insert(&mut self, value: T) {
println!("Node insert");
match self.left {
Some(ref mut l) => {
match self.right {
Some(ref mut r) => {
r.insert(value);
}
None => {
self.right = Some(Box::new(Node::new(Some(value), None, None)));
}
}
}
None => {
self.left = Some(Box::new(Node::new(Some(value), None, None)));
}
}
}
}
impl<T> std::fmt::Display for Node<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f,
"Node data: {} left: {:?}, right: {:?}",
self.data,
self.left,
self.right);
}
}
impl<T> std::fmt::Debug for Node<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f,
"Node data: {} left: {:?}, right: {:?}",
self.data,
self.left,
self.right);
}
}
impl<T> Iterator for NodeIterator<T> {
type Item = Node<T>;
fn next(&mut self) -> Option<Node<T>> {
if self.nodes.len() == 0 {
None
} else {
let current: Option<Node<T>> = self.nodes.pop();
for it in current.iter() {
for n in it.left.iter() {
self.nodes.push(**n);
}
for n in it.right.iter() {
self.nodes.push(**n);
}
}
return current;
}
}
}
impl<T> Tree<T> {
pub fn new() -> Tree<T> {
Tree { root: None }
}
pub fn insert(&mut self, value: T) {
match self.root {
Some(ref mut n) => {
println!("Root is not empty, insert in node");
n.insert(value);
}
None => {
println!("Root is empty");
self.root = Some(Node::new(Some(value), None, None));
}
}
}
fn iter(&self) -> NodeIterator<T> {
NodeIterator { nodes: vec![self.root.unwrap()] }
}
}
fn main() {
println!("Hello, world!");
let mut tree: Tree<i32> = Tree::new();
tree.insert(42);
tree.insert(43);
for it in tree.iter() {
println!("{}", it);
}
}