how can i return Null in Rust function?
#[derive(Debug, Clone)]
struct NodeValue {
id: String,
parent: String,
children: Vec<NodeValue>,
}
impl NodeValue {
fn find_parent(&self, id: &mut String) -> &NodeValue {
if self.id == *id {
println!("{},{}", self.id, id);
return self;
}
for child in &self.children {
println!("{:?}", child);
let res = child.find_parent(id);
return res;
}
return null; //return null
}
}
fn main() {
let root = NodeValue {
id: "#".to_string(),
parent: String::from("root"),
children: vec![],
};
let id = "1";
let mut parent = "#";
let mut parent_node = root.find_parent(&mut parent);
let node1 = NodeValue {
id: "2".to_string(),
parent: "1".to_string(),
children: vec![],
};
parent_node.children.push(node1);
}
my code in playground
You cannot return null
in Rust, because there is no such concept in the language. Instead you should use Option<T>
:
fn find_parent(&self, id: &mut String) -> Option<&NodeValue> {
if self.id == *id {
println!("{},{}", self.id, id);
return Some(self);
}
//This loop is pointless, I've kept it because it's in your original code
for child in &self.children {
println!("{:?}", child);
return child.find_parent(id);
}
None
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With