我有一个结构Foo
:
struct Foo {
v: String,
// Other data not important for the question
}
我想处理数据流并将结果保存到Vec<Foo>
,并在字段Vec<Foo>
上为此Foo::v
创建一个索引。
我想为索引使用HashMap<&str, usize>
,其中的键将为&Foo::v
,值是Vec<Foo>
中的位置,但我愿意接受其他建议。
我想尽可能快地处理数据流,这不需要做两次明显的事情。
例如,我想:
String
一次Rc
或RefCell
来增加运行时间。借阅检查器不允许此代码:
let mut l = Vec::<Foo>::new();
{
let mut hash = HashMap::<&str, usize>::new();
//here is loop in real code, like:
//let mut s: String;
//while get_s(&mut s) {
let s = "aaa".to_string();
let idx: usize = match hash.entry(&s) { //a
Occupied(ent) => {
*ent.get()
}
Vacant(ent) => {
l.push(Foo { v: s }); //b
ent.insert(l.len() - 1);
l.len() - 1
}
};
// do something with idx
}
存在多个问题:
hash.entry
借用密钥,因此s
的生存期必须比hash
大”s
,而我在行(a)处具有只读引用所以我应该如何实现这种简单的算法而又不需额外调用String::clone
或在调用HashMap::get
之后再调用HashMap::insert
?
我有一个struct Foo:struct Foo {v:字符串,//对这个问题不重要的其他数据}我想处理数据流并将结果保存到Vec
一般
不使用
Rc
或RefCell
来增加运行时间。
错误是: