我不太明白为什么Rust不喜欢我的remove_str方法:
use std::cell::RefCell;
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq)]
struct StringWrap<'a>{
s: &'a String,
}
struct Container<'a>{
m: HashSet<StringWrap<'a>>
}
impl<'a> Container<'a>{
fn remove_str(&mut self, s: &str){
let string = String::from(s);
let to_remove = StringWrap{s: &string};
self.m.remove(&to_remove);
}
}
它会出现以下问题:
error[E0597]: `string` does not live long enough
--> tests/worksheet.rs:17:39
|
14 | impl<'a> Container<'a>{
| -- lifetime `'a` defined here
...
17 | let to_remove = StringWrap{s: &string};
| ^^^^^^^ borrowed value does not live long enough
18 | self.m.remove(&to_remove);
| ------------------------- argument requires that `string` is borrowed for `'a`
19 | }
| - `string` dropped here while still borrowed
据我所见,我的
string
和to_remove
的寿命足够长,可以允许.remove
调用完成其工作。这是因为remove可能是异步的还是其他什么原因呢?感谢任何帮助或见解!
StringWrap
结构体中使用了s: &String
,但这并不必要--只需使用s: String
,就不需要生命周期了。 - Herohtar关闭
投票。很明显HashSet
可能包含拥有的字符串,但是OP请求帮助更好地理解为什么这行不通。 - at54321