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>>
还是有替代方案?请注意,我正在编写“库”代码,以便可以更改它。