#Rust trait lifetime

2 messages · Page 1 of 1 (latest)

narrow burrow
#

Hey !
I struggle a bit with lifetimes...

I have a the following trait :

trait InitResult {
    fn init(&mut self, keys: &[&str]) -> &mut i32;
}

impl<V> InitResult for HashMap<&str, V>
where
    V: InitResult + Default,
{
    fn init(&mut self, keys: &[&str]) -> &mut i32 {
        if let Some((first, rest)) = keys.split_first() {
            let entry = self.entry(*first).or_default();
            entry.init(rest)
        } else {
            panic!("")
        }
    }
}

impl InitResult for i32 {
    fn init(&mut self, keys: &[&str]) -> &mut i32 {
        if !keys.is_empty() {
            panic!("Expected to reach the end of keys slice but found more keys");
        }
        self
    }
}

the idea is to call it like this :

let mut result: HashMap<&str, HashMap<&str, HashMap<&str, i32>>> = HashMap::new();

*result.init(&[account, "general", "views"]) += 1;

println!("{:#?}", result);

If someone is able to help 🙂

Here is the error:

past trout
#

you must introduce a lifetime parameter to indicate that the HashMap cannot outlive the string slices it stores:

//              vvvv
trait InitResult<'a> {
    fn init(&mut self, keys: &[&'a str]) -> &mut i32;
}

impl<'a, V> InitResult<'a> for HashMap<&'a str, V>
where
    V: InitResult<'a> + Default,
{
    fn init(&mut self, keys: &[&'a str]) -> &mut i32 {
        if let Some((first, rest)) = keys.split_first() {
            let entry = self.entry(*first).or_default();
            entry.init(rest)
        } else {
            panic!("")
        }
    }
}

impl InitResult<'_> for i32 {
    fn init(&mut self, keys: &[&str]) -> &mut i32 {
        if !keys.is_empty() {
            panic!("Expected to reach the end of keys slice but found more keys");
        }
        self
    }
}