我在 Mutex 中遇到了可变借用失败的错误。
这是代码。
现在没问题了。但是,如果取消注释将 state
包装成 Mutex 并解包它,编译将会失败。
为什么 Mutex 会有所不同呢?
use std::collections::HashMap;
use std::sync::Mutex;
struct State {
h1: HashMap<String, String>,
h2: HashMap<String, String>,
}
fn main() {
let mut state = State {
h1: HashMap::new(),
h2: HashMap::new(),
};
// It fails to compile if uncommenting these 2 lines!
//let state = Mutex::new(state);
//let mut state = state.lock().unwrap();
let v1 = state.h1.get_mut("abc").unwrap();
let v2 = state.h2.get_mut("abc").unwrap();
v1.push_str("123");
v2.push_str("123");
}
取消注释2行代码后的错误:
error[E0499]: cannot borrow `state` as mutable more than once at a time
--> tmp.rs:20:14
|
19 | let v1 = state.h1.get_mut("abc").unwrap();
| ----- first mutable borrow occurs here
20 | let v2 = state.h2.get_mut("abc").unwrap();
| ^^^^^ second mutable borrow occurs here
21 | v1.push_str("123");
| -- first borrow later used here
如果改变一些代码顺序也没问题:
let state = Mutex::new(state);
let mut state = state.lock().unwrap();
let v1 = state.h1.get_mut("abc").unwrap();
v1.push_str("123");
let v2 = state.h2.get_mut("abc").unwrap();
v2.push_str("123");
< p > 看起来v1
持有state
的引用。如果v1
结束,它会丢弃引用,然后可以再次借用state
。
为什么v1
持有state
的引用?
====编辑====
@Alexey Larionov给出了答案。我发现一个类似的问题。我需要通过deref_mut()
手动从MutexGuard中获取state
。因此,添加这一行就可以解决问题:
let state = state.deref_mut();