How to get mutable struct from HashMap?

安稳与你 提交于 2019-12-06 09:51:20

A fundamental idea in Rust is: either Aliasing or Mutability, but not both.

Aliasing means having multiple active pointers to the same value.

What is Rc<T>? It's sharing ownership, aliasing a value. Thus Rc<T> does not allow mutating the value inside.

There is a way around this with Rc, to use interior mutability with types like either Cell<U> or 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.)

  • Rc<Cell<U>> allows mutating U by only allowing write-in and read-out, but no pointers to the inner U value. 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. No aliasing, you have mutability!

Links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!