简体   繁体   English

如何从HashMap获取可变结构?

[英]How to get mutable struct from HashMap?

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) . 我有一个针对我所有状态的HashMap<String, Rc<State>> ,它是HashMap<String, Rc<State>> ,我想调用当前状态的成员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();
}
...

Here's the error: 这是错误:

src/main.rs:70:25: 70:33 error: cannot borrow immutable borrowed content as mutable
src/main.rs:70                         (*state).shutdown();`

afaict from the documentation, the problem is that get_mut returns a mutable reference to the state, not a reference to a mutable state. 从文档来看,问题在于get_mut返回对该状态的可变引用,而不是对可变状态的引用。 So how would I get a reference to a mutable state? 那么我如何获得对可变状态的引用?

A fundamental idea in Rust is: either Aliasing or Mutability, but not both. Rust中的一个基本思想是: 别名或可变性,但不能同时存在。

Aliasing means having multiple active pointers to the same value. 混叠意味着具有指向相同值的多个活动指针。

What is Rc<T> ? 什么是Rc<T> It's sharing ownership, aliasing a value. 它共享所有权,给值起别名。 Thus Rc<T> does not allow mutating the value inside. 因此, Rc<T>不允许对内部的值进行突变。

There is a way around this with Rc , to use interior mutability with types like either Cell<U> or RefCell<U> . 使用Rc可以解决此问题,可以将内部可变性Cell<U>RefCell<U>类的类型一起使用。

(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.) (如果编写多线程程序,则将Arc用于线程安全共享所有权/别名,而可以将Mutex<U>用于线程安全内部可变性。)

  • Rc<Cell<U>> allows mutating U by only allowing write-in and read-out, but no pointers to the inner U value. Rc<Cell<U>>允许突变U通过只允许写入和读出,但没有指针到内U值。 No pointers, no aliasing! 没有指针,没有锯齿!

  • 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. Rc<RefCell<U>>允许通过方法.borrow_mut()进行.borrow_mut() ,该方法将在运行时保留借用计数,并动态确保任何可变借用都是排他的。 No aliasing, you have mutability! 没有别名,您具有可变性!

Links 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM