gpt4 book ai didi

rust - 在 Rc 包装的对象中调用可变方法的标准方法是什么?

转载 作者:行者123 更新时间:2023-11-29 08:22:42 25 4
gpt4 key购买 nike

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

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 函数来实现此目的,但我不知道这是否是实现此目的的标准方法。

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

最佳答案

documentation for Rc 说:

See the module-level documentation for more details.

其中有这段文字:

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 文档,您可能会选择阅读 The Rust Programming Language 中的整个 chapter about 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.


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

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

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

另见:

I am using the get_mut function

您不太可能想使用它。

另见:

关于rust - 在 Rc 包装的对象中调用可变方法的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52994205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com