Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rust - "borrowed value does not live long enough" seems to blame the wrong thing

I am counting the number of times a word appears in Macbeth:

use std::io::{BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;

fn main() {
    let f = File::open("macbeth.txt").unwrap();
    let reader = BufReader::new(f);
    let mut counts = HashMap::new();

    for l in reader.lines() {
        for w in l.unwrap().split_whitespace() {
            let count = counts.entry(w).or_insert(0);
            *count += 1;
        }
    }

    println!("{:?}", counts);
}

Rust barfs on this, saying:

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:14:9
   |
11 |         for w in l.unwrap().split_whitespace() {
   |                  ---------- temporary value created here
...
14 |         }
   |         ^ temporary value dropped here while still borrowed
...
18 | }
   | - temporary value needs to live until here
   |
   = note: consider using a `let` binding to increase its lifetime

The actual problem is that w is a reference, and so changing it to w.to_string() solves it. I don't get why the Rust compiler is pointing the blame at l, when the issue is w. How am I supposed to infer that w is the problem here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

is pointing the blame at l

It's not, really. Review the error message again:

     for w in l.unwrap().split_whitespace() {
              ---------- temporary value created here

The error marker is pointing to the call of unwrap on l.

when the issue is w

It's not, really. l is of type Result<String>. When you call unwrap, you get a String, and then split_whitespace returns references to that string. These references live only as long as the string, but your code tries to put them into a hashmap that will live longer than the string. The problem is that the l.unwrap() doesn't live long enough, and w is just a reference to the thing that doesn't live long enough.

Conceptually, it's the same problem as this code:

use std::collections::HashMap;

fn main() {
    let mut counts = HashMap::new();

    {
        let s = String::from("hello world");
        counts.insert(&s, 0);
    }

    println!("{:?}", counts);
}

Which also points to s and says it doesn't live long enough (because it doesn't).

The correct solution is to convert each word into an owned String which the HashMap can then hold:

for l in reader.lines() {
    for w in l.unwrap().split_whitespace() {
        counts.entry(w.to_string()).or_insert(0) += 1;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...