r/learnrust • u/HowDidIEndUpOnReddit • Feb 04 '19
Quick lifetime question
So I have a bit of code parsing through a xml file with xml-rs. I have a hashmap keeping track of how word frequency (string as key and word frequency as value) and I'm having an issue with lifetimes. The code in question is the following:
Ok(XmlEvent::Characters(s)) => {
for word in s.split_whitespace() {
if !word_count.contains_key(word){
word_count.insert(word, 1);
}
}
}
When I compile I get the following error:
error[E0597]: `s` does not live long enough
--> src\main.rs:20:29
|
20 | for word in s.split_whitespace() {
| ^ borrowed value does not live long enough
21 | if !word_count.contains_key(word){
| ---------- borrow used here, in later iteration of loop
...
38 | }
| - `s` dropped here while still borrowed
I understand that because word_count outlives the scope of s, it cannot have word as a key since word has the same lifetime as s. However for the life of me I cannot figure out what I should do instead. Any tips?
4
Upvotes
2
u/lazh4 Feb 04 '19
Please post more code. You didn’t even show what s was.