作者:制霸 | 来源:互联网 | 2022-12-05 21:18
例如,给出此代码:
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>
}
impl LibraryStruct {
pub fn data(&self) -> Rc> {
self.data.clone()
}
}
// Receives data field from LibraryStruct.data()
struct A {
data: Rc>
}
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>
还是有替代方案?注意我正在写"库"代码,所以我可以改变它.
1> Peter Hall..:
如果你分享一个,RefCell
那么总是可以改变它 - 这基本上是它的全部要点.鉴于您可以更改其实现LibraryStruct
,您可以确保它data
不公开,并通过getter方法控制它向用户公开的方式:
pub struct LibraryStruct {
// note: not pub
data: Rc>
}
impl LibraryStruct {
// could also have returned `Ref<'a, LibraryData> but this hides your
// implementation better
pub fn data<'a>(&'a self) -> impl Deref + 'a {
self.data.borrow()
}
}
在您的其他结构中,您可以通过将其视为参考来保持简单:
pub struct A<'a> {
data: &'a LibraryData,
}
impl<'a> A<'a> {
pub fn do_something(&self) {
// self.data is only available immutably here because it's just a reference
}
}
fn main() {
let ld = LibraryData {};
let ls = LibraryStruct { data: Rc::new(RefCell::new(ld)) };
let a = A { data: &ls.data() };
}
如果您需要保留引用更长时间,在此期间原始RefCell
需要在库代码中可变地借用,那么您需要创建一个可以管理它的自定义包装器.可能有一个标准的库类型,但我不知道它,并且很容易为您的用例专门制作一些东西:
// Wrapper to manage a RC and make it immutably borrowable
pub struct ReadOnly {
// not public
inner: Rc>,
}
impl ReadOnly {
pub fn borrow<'a>(&'a self) -> impl Deref + 'a {
self.inner.borrow()
}
}
现在在库代码中返回:
impl LibraryStruct {
pub fn data<'a>(&'a self) -> ReadOnly {
ReadOnly { inner: self.data.clone() }
}
}
当您使用它时,内部RefCell
将无法直接访问,并且数据仅可用于不可靠地借用:
pub struct A {
data: ReadOnly,
}
impl A {
pub fn do_something(&self) {
// data is immutable here
let data = self.data.borrow();
}
}
fn main() {
let ld = LibraryData {};
let ls = LibraryStruct { data: Rc::new(RefCell::new(ld)) };
let a = A { data: ls.data() };
}