是否有替代或方式有Rc >那限制了X的可变性?

问题描述 投票:6回答:1

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>>或有替代?注意我正在写“库”代码,所以我可以改变它。

rust immutability interior-mutability
1个回答
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() };
}
© www.soinside.com 2019 - 2024. All rights reserved.