是否有其他替代方法或方法可以使Rc <refcell <x >>限制X的可变性?

时间:2018-09-01 20:18:44

标签: rust immutability interior-mutability

For example given this code

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
    }
}

如何防止LibraryDataLibraryStruct之外进行突变? LibraryStruct应该是唯一能够在其方法中变异data的人。 Rc<RefCell<LibraryData>>有可能吗?还是有替代方法?请注意,我正在编写“库”代码,以便可以对其进行更改。

1 个答案:

答案 0 :(得分:7)

如果您共享一个RefCell,则始终可以对其进行突变-本质上就是它的重点。既然您能够更改LibraryStruct的实现,则可以确保data不公开,并通过getter方法控制如何向用户公开它:

pub struct LibraryStruct {
    // note: not pub
    data: Rc<RefCell<LibraryData>>
}

impl LibraryStruct {
    // could also have returned `Ref<'a, LibraryData> but this hides your 
    // implementation better
    pub fn data<'a>(&'a self) -> impl Deref<Target = LibraryData> + '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<RefCell> and make it immutably borrowable
pub struct ReadOnly<T> {
    // not public
    inner: Rc<RefCell<T>>,
}

impl<T> ReadOnly<T> {
    pub fn borrow<'a>(&'a self) -> impl Deref<Target = T> + 'a {
        self.inner.borrow()
    }
}

现在在您的库代码中返回此代码:

impl LibraryStruct {
    pub fn data<'a>(&'a self) -> ReadOnly<LibraryData> {
        ReadOnly { inner: self.data.clone() }
    }
}

当您使用它时,内部的RefCell将无法直接访问,并且数据只能一成不变地借用:

pub struct A {
    data: ReadOnly<LibraryData>,
}

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() };
}