use std::rc::Rc;
use std::cell::RefCell;
// Don't want to copy for performance reasons
struct LibraryData {
// Fields ...
}
// Creates and mutates data field in methods
struct LibraryStruct {
// Only LibraryStruct should have mutable access to this
data: Rc<RefCell<LibraryData>>
}
impl LibraryStruct {
pub fn data(&self) -> Rc<RefCell<LibraryData>> {
self.data.clone()
}
}
// Receives data field from LibraryStruct.data()
struct A {
data: Rc<RefCell<LibraryData>>
}
impl A {
pub fn do_something(&self) {
// Do something with self.data immutably
// I want to prevent this because it can break LibraryStruct
// Only LibraryStruct should have mutable access
let data = self.data.borrow_mut();
// Manipulate data
}
}
我该如何防止LibraryData
在LibraryStruct
之外被改变?LibraryStruct
应该是唯一能够在其方法中改变data
的对象。使用Rc<RefCell<LibraryData>>
是否可行,还是有其他替代方案?需要注意的是,我正在编写“library”代码,因此可以对其进行更改。