Borrowed value does not live long enough Exercise CH8

Hello,
I'm trying to resolve the last exercise in ch8 from: Storing Keys with Associated Values in Hash Maps - The Rust Programming Language, but for many ways I trying to change the code, I can't get resolve the lifetime problem. The code is at: Rust Playground.
As a side note, it's supposed to study lifetime in later chapters, not in ch8...so must be a simpler solution for this problem.

Thank you in advance.

Yes, by letting your hash map take ownership of the keys and values it stores. Instead of storing string slices, you could store Strings or Cow<'static, String>s Cow<'static, str>s. Here an example with String.

Hello @jofas, I create a hashmap with load_data() function: let mut company_map: HashMap<&str, &str> = load_data(); So you are saying that I change &str type to Strings as a first solution, but I don't understand the other one. Could you give me an example with code?
Thank you!

Sure, here's an example with Cow. Note that above I said that you should use Cow<'static, String>, which is the wrong type. You should use Cow<'static, str> instead, my mistake.

1 Like

Solved! Using Strings: Rust Playground. Thank you for you time @jofas. I can continue reading the following chapters...

1 Like

The paradigm is

// First: NLL (the current borrow checker implementation) is based 
// on control flow graph and the type of HashMap is instantiated 
// in one branch and stores local references.
// This is fine as long as you only use the map exactly once in if-else, 
// because this won't cause dangling references.
fn ok() {
    let mut map = HashMap::new();
    if false {
        let s = String::from("");
        let ss = &*s;
        map.insert(ss, ss);
    } else {
        dbg!(&map);
    }
}
// error[E0597]: `s` does not live long enough
fn failed_1() {
    let mut map = HashMap::new();
    if false {
        let s = String::from("");
        let ss = &*s;
        map.insert(ss, ss);
    } else {
        &map;
    }
    &map; // This causes dangling references, because `ss` is borrowed
    // from a local owned String which lies in one branch above and [drops] in if body
    // [drops]: https://doc.rust-lang.org/reference/destructors.html#temporary-scopes
}
// Your code can be simplified as follows.

// Same error with same reason: map stores a local reference the owner 
// of which drops in each iteration.

// error[E0597]: `s` does not live long enough
fn failed_2() {
    let mut map = HashMap::new();
    loop {
        if false {
            let s = String::from("");
            let ss = &*s;
            map.insert(ss, ss);
        } else {
            &map;
        }
    }
}

Thank you for point out: 2094-nll - The Rust RFC Book.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.