'Expected struct `std::boxed::Box`, found `i32`
I am trying to instantiate an object of a BSTNode struct. But when I try to use the insert method I've implemented I am getting an error saying Expected struct 'std::boxed::Box' found 'i32', but inside the function my parameters are '&mut self' and 'i32', and to use the func from main I do something like that:
let mut root: Option<Box<BSTNode>> = Some(Box::new(BSTNode {
value: 0,
left: None,
right: None,
}));
root.insert(15);
but the insert func generates the error above.
BST Insert func:
pub fn insert(&mut self, val: i32) {
if val <= self.value {
match self.left {
//If there are no nodes on the left, insert a new heap-allocated BSTNode holding the value passed to the fn
None => {
self.left = Some(Box::new(BSTNode {
value: val,
left: None,
right: None,
}))
}
//If there's a node found on the left, recursively call the fn again on the node found.
Some(ref mut node) => node.insert(val),
}
} else {
match self.right {
//If there are no nodes on the right, insert a new heap-allocated BSTNode holding the value passed to the fn
None => {
self.right = Some(Box::new(BSTNode {
value: val,
left: None,
right: None,
}))
}
//If there's a node found on the right, recursively call the fn again on the node found.
Some(ref mut node) => node.insert(val),
}
}
}
BSTNode struct:
pub struct BSTNode {
pub value: i32,
//Hold a possibly-nullable pointer to a heap-allocated object -BSTNode
pub left: Option<Box<BSTNode>>,
pub right: Option<Box<BSTNode>>,
}
What am I missing? why can't I use the insert func properly?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
