Quantcast
Channel: User trojanfoe - Stack Overflow
Viewing all articles
Browse latest Browse all 226

Answer by trojanfoe for Optionally reference parent struct

$
0
0

You need to specify the life time of the reference to the parent. Something like this:

use std::collections::HashMap;#[derive(Debug)]struct Value {    _value: String,}impl Value {    fn new(value: &str) -> Self {        Self { _value: value.to_string() }    }}struct Scope<'a> {    values: HashMap<String, Value>,    parent: Option<&'a Scope<'a>>,}impl<'a> Scope<'a> {    fn new(parent: Option<&'a Scope>) -> Scope<'a> {        Scope {            values: HashMap::new(),            parent,        }    }    pub fn add_value(&mut self, name: &str, val: Value) {        self.values.insert(name.to_string(), val);    }    pub fn get_value(&self, name: &str) -> Option<&Value> {        self.values.get(name)    }    pub fn get_parent_value(&self, name: &str) -> Option<&Value> {        match self.parent {            Some(scope) => scope.get_value(name),            None => None        }    }}fn main() {    let mut parent = Scope::new(None);    parent.add_value("parent_name", Value::new("parent_value"));    let mut child = Scope::new(Some(&parent));    child.add_value("child_name", Value::new("child_value"));    println!("child value: {:?}", child.get_value("child_name"));    println!("parent value: {:?}", child.get_parent_value("parent_name"));}

Output:

child value: Some(Value { _value: "child_value" })parent value: Some(Value { _value: "parent_value" })

Rust Playground

Note: better semantics for get_value() would probably be to see if the value exists in self.values and if not try the parent; this would continue until no more parents exist.


Viewing all articles
Browse latest Browse all 226

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>