如何从HashMap获取可变结构? [英] How to get mutable struct from HashMap?
问题描述
我有一个所有状态的哈希图,它是一个 HashMap
,我想调用当前状态的成员 fn init(&mut self)
.但是我收到以下代码的错误:
I have a hashmap for all my states, which is a HashMap<String, Rc<State>>
, and I want to call the current state's member fn init(&mut self)
. But I'm getting an error with the following code:
...
if let Some(state) = self.states.get_mut(state_id) {
(*state).init();
}
...
错误如下:
src/main.rs:70:25: 70:33 error: cannot borrow immutable borrowed content as mutable
src/main.rs:70 (*state).shutdown();`
来自文档,问题在于 get_mut
返回对状态的可变引用,而不是对可变状态的引用.那么我如何获得对可变状态的引用?
afaict from the documentation, the problem is that get_mut
returns a mutable reference to the state, not a reference to a mutable state. So how would I get a reference to a mutable state?
推荐答案
Rust 的一个基本思想是:别名或可变性,但不能两者兼而有之.
A fundamental idea in Rust is: either Aliasing or Mutability, but not both.
别名意味着有多个指向相同值的活动指针.
Aliasing means having multiple active pointers to the same value.
什么是Rc
?它是共享所有权,别名一个值.因此 Rc
不允许改变里面的值.
What is Rc<T>
? It's sharing ownership, aliasing a value. Thus Rc<T>
does not allow mutating the value inside.
Rc
有一种解决方法,可以将内部可变性与 Cell<U>
或 RefCell< 等类型一起使用;U>
.
There is a way around this with Rc
, to use interior mutability with types like either Cell<U>
or RefCell<U>
.
(如果你编写一个多线程程序,你会使用 Arc
来保证线程安全的共享所有权/别名,你可以使用 Mutex
来保证线程安全的内部改为可变性.)
(If you write a multithreaded program, you'd use Arc
for thread safe shared ownership / aliasing, and you could use Mutex<U>
for thread safe interior mutability instead.)
Rc
允许改变> | U
,只允许写入和读出,但没有指向内部U
值.没有指针,没有别名!
Rc<Cell<U>>
allows mutatingU
by only allowing write-in and read-out, but no pointers to the innerU
value. No pointers, no aliasing!
Rc
允许通过方法 .borrow_mut()
进行变异,该方法将在运行时保持借用计数并动态确保任何可变借用都是排他性的.没有混叠,你有可变性!
Rc<RefCell<U>>
allows mutating by the method .borrow_mut()
that will keep a borrow count at runtime and dynamically make sure that any mutable borrow is exclusive. No aliasing, you have mutability!
链接
这篇关于如何从HashMap获取可变结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!