在 Rc 包装的对象中调用可变方法的标准方法是什么? [英] What is the standard way to call a mutable method in a Rc-wrapped object?

查看:49
本文介绍了在 Rc 包装的对象中调用可变方法的标准方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图通过调用其方法之一来更改引用计数对象的值:

In the following code, I am trying to change the value of a refcounted object by calling one of its methods:

use std::rc::Rc;

fn main() {
    let mut x = Rc::new(Thing { num: 50 });
    x.what_to_do_to_get_mut_thing().change_num(19); //what do i do here
}

pub struct Thing {
    pub num: u32,
}

impl Thing {
    pub fn change_num(&mut self, newnum: u32) {
        self.num = newnum;
    }
}

我正在使用 get_mut 函数来实现此目的,但我不知道这是否是实现此目的的标准方法.

I am using the get_mut function to achieve this, but I don't know if this is a standard way to accomplish this.

if let Some(val) = Rc::get_mut(&mut x) {
    val.change_num(19);
}

推荐答案

Rc 的文档说:

有关详细信息,请参阅模块级文档.

See the module-level documentation for more details.

其中有这段文字:

这很困难,因为 Rc 通过仅提供对其包装的值的共享引用来强制内存安全,并且这些不允许直接更改.我们需要将我们希望改变的部分值包装在一个 RefCell 中,它提供了内部可变性:一种通过共享引用实现可变性的方法.RefCell 强制执行 Rust 的借用规则在运行时.

This is difficult because Rc enforces memory safety by only giving out shared references to the value it wraps, and these don't allow direct mutation. We need to wrap the part of the value we wish to mutate in a RefCell, which provides interior mutability: a method to achieve mutability through a shared reference. RefCell enforces Rust's borrowing rules at runtime.

然后演示如何使用它.

如果您没有阅读 API 文档,您可能会选择阅读整个 Rust 编程语言中关于 Rc 的章节.它是这样说的:

If you didn't read the API documentation, you might have instead chosen to read the entire chapter about Rc in The Rust Programming Language. It has this to say:

通过不可变引用,Rc 允许您在程序的多个部分之间共享数据以供只读.如果 Rc 也允许你有多个可变引用,你可能会违反第 4 章中讨论的借用规则之一:对同一位置的多个可变借用会导致数据竞争和不一致.但是能够变异数据是非常有用的!在下一节中,我们将讨论内部可变性模式和 RefCell 类型,您可以将其与 Rc 结合使用以处理它不变性限制.

Via immutable references, Rc<T> allows you to share data between multiple parts of your program for reading only. If Rc<T> allowed you to have multiple mutable references too, you might violate one of the borrowing rules discussed in Chapter 4: multiple mutable borrows to the same place can cause data races and inconsistencies. But being able to mutate data is very useful! In the next section, we’ll discuss the interior mutability pattern and the RefCell<T> type that you can use in conjunction with an Rc<T> to work with this immutability restriction.


将这些新知识应用到您的代码中:


Applying this new knowledge to your code:

use std::{cell::RefCell, rc::Rc};

fn main() {
    let x = Rc::new(RefCell::new(Thing { num: 50 }));
    x.borrow_mut().change_num(19);
}

另见:

我正在使用 get_mut 函数

您不太可能想要使用它.

It's very unlikely that you want to use this.

另见:

这篇关于在 Rc 包装的对象中调用可变方法的标准方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆