如何在Rust函数中返回Null?
#[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);
}
答案 0 :(得分:4)
您无法在Rust中返回null
,因为该语言中没有这样的概念。相反,您应该使用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
}