我正在尝试使此工作生效
use std::collections::HashMap;
struct Test1 {
total: u32,
hash: HashMap<u32, u32>,
}
impl Test1 {
fn new() -> Test1 {
Test1 {
total: 0,
hash: HashMap::new(),
}
}
fn add(&mut self) -> u32 {
self.total += 1;
self.total
}
fn get_or_create(&mut self, id: u32) -> u32 {
match self.hash.get(&id) {
Some(value) => *value,
None => {
let value = self.add();
self.hash.insert(id, value);
value
}
}
}
}
fn main() {
let mut test = Test1::new();
println!("{:?}", test.get_or_create(1));
println!("{:?}", test.get_or_create(1));
}
(playpen)[http://is.gd/hDLEaL]
但我得到了
<anon>:25:33: 25:37 error: cannot borrow `*self` as mutable because `self.hash` is also borrowed as immutable [E0502]
删除模式匹配并不能解决问题,但我不明白为什么。
match self.hash.get(&id) {
改为match self.hash.get(&id).cloned() {
,并将*value
改为value
。 - qthreeget
返回的是Option<&u32>
,但实际上你不需要那个借用引用,只需要值。所以cloned()
将Option<&T>
转换为Option<T>
并释放了借用。 - qthree.entry().or_insert()
:https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.entry - starblue