Hereās a confusing one:
use std::collections::HashMap;
struct WordGraph<'a> {
g: HashMap<&'a str, Box<Vec<&'a str>>>,
}
impl <'a> WordGraph<'a> {
fn new() -> WordGraph<'a> { WordGraph{g: HashMap::new(),} }
fn insert_word<'a>(&self, s: &'a str) {
if (!self.g.contains_key(&s)) {
self.g.insert(s, box Vec::new());
}
}
}
fn main() {
let mut wg = WordGraph::new();
let words = vec!("one" , "two" , "one" , "three" , "two" , "four");
for w in words.iter() { wg.insert_word(*w); }
}
The compilerās āconsiderā¦ā suggestion is less then helpful. From this playpen:
<anon>:10:14: 10:37 error: cannot infer an appropriate lifetime due to conflicting requirements
<anon>:10 if (!self.g.contains_key(&s)) {
^~~~~~~~~~~~~~~~~~~~~~~
<anon>:11:25: 11:26 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
<anon>:11 self.g.insert(s, box() Vec::new());
^
<anon>:9:5: 13:6 help: consider using an explicit lifetime parameter as shown: fn insert_word<'a>(&self, s: &'a str)
<anon>:9 fn insert_word<'a>(&self, s: &'a str) {
<anon>:10 if (!self.g.contains_key(&s)) {
<anon>:11 self.g.insert(s, box() Vec::new());
<anon>:12 }
<anon>:13 }
error: aborting due to 2 previous errors
As you can see, the suggested function signature is exactly what I have⦠I donāt have a solution yet. This is intended to be an adjacency-list representation of a graph where the nodes are slices into strings (or 'static &str refs) that are owned elsewhere, and where the lifetime of the references can be proven to outlive the HashMap/WordGraph itself.
I suspect the compiler message is a bug, but that aside, how would I solve this issue?