Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Null in Rust function [duplicate]

Tags:

null

rust

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

like image 895
Hossein Akbarzadeh Avatar asked Dec 10 '22 02:12

Hossein Akbarzadeh


1 Answers

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
}
like image 110
Svetlin Zarev Avatar answered Jan 25 '23 02:01

Svetlin Zarev