语境
作为练习,我尝试在 Rust中重新实现https://github.com/urbanairship/sarlacc-pit 。
Sarlacc-pit 将外部源镜像到内存数据结构(Set/Map/Etc)中。图书馆的客户纯粹根据馆藏进行操作,不知道馆藏内容正在发生变化。
问题
客户端需要保持对集合的不可变引用,而单个更新线程保持可变引用以更新其内容。这直接违反了 rust 的保证,但在这种情况下应该是安全的,具有以下粗略结构:
pub struct Map<K, V> {
delegate: SomeReferenceType<Arc<HashMap<K, V>>>
}
impl<K, V> Map<K, V> {
pub fn get(&self, k: &K) -> Option<&V> {
self.delegate.borrow().get(k)
}
fn update(&mut self, new_delegate: HashMap<K, V>) {
self.delegate.set(Arc::new(new_delegate));
}
}
pub struct UpdateService<K, V> {
collection: Arc<Map<K, V>>
}
impl<K, V> UpdateService<K ,V> {
pub fn get_collection(&self) -> Arc<Map<K, V>> {
collection.clone()
}
// Called from a thread run on a cadence
fn update_collection(&mut self) {
let new_value = /* fetch and process value from backing store */
self.collection.borrow_mut().update(new_value);
}
}
我意识到,由于多种原因,这无法编译。
问题的核心是:SomeReferenceType 的类型应该是什么,才能允许这些可变和不可变的引用在没有 ReadWriteLock 之类的东西的情况下共存?我错过了什么吗?