我在处理包含 rust HashMap 的结构时遇到问题。
假设我有以下类型:
pub type KeyType i32;
pub enum StatusType { Locked, Unlocked }
pub struct Entry {
key: KeyType,
status: StatusType
}
pub struct Manager<'a> {
map: HashMap<KeyType, &'a mut Entry>
}
我想在管理器上定义一个方法,它接受一个键,如果没有找到则返回一个未锁定的条目,如果存在则返回现有的条目。这是伪代码:
impl<'a> Manager<'a> {
pub fn find_or_create_entry(&'a mut self, key: KeyType) -> &'a mut Entry {
match self.map.get(&key) {
Some(e) => e,
None => {
// create new entry, add to map, and return mutable ref
}
}
}
}
我一直无法弄清楚这在 Rust 中是如何工作的。有什么指点吗?
最佳答案
我通过将 HashMap 的类型更改为 HashMap<KeyType,Box<Entry>>
来解决这个问题, 并实现了如下方法:
pub fn get_or_create_entry(& mut self, key: LockKey) -> &mut LockEntry {
let e = Box::new(LockEntry{key: key, status: LockStatus::Unlocked});
self.lock_table.entry(key).or_insert(e)
}
有没有更好的办法?
关于hashmap - 如何为包含具有可变引用的 HashMap 的结构实现 find_or_create 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427944/