在 Rust 函数中返回 Null



如何在 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);
}

我在操场上的代码

你不能在 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
}

相关内容

  • 没有找到相关文章