gpt4 book ai didi

rust - Mutex 中的可变借用失败

转载 作者:行者123 更新时间:2023-12-04 12:54:10 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Error while trying to borrow 2 fields from a struct wrapped in RefCell

(1 个回答)


2个月前关闭。




我收到有关 Mutex 中可变借用失败的错误。
这是代码。
现在好了。但是如果取消注释这 2 行,它将编译失败,这 2 行包装了 state进入一个互斥体并解开它。
为什么互斥量会有所不同?

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");
看来 v1持有 state 的引用.如 v1结束,它删除引用,然后 state可以再借。
为什么 v1持有 state 的引用?
====编辑====
@Alexey Larionov 给出了答案。我发现了一个类似的 question .我应该得到 state手动退出 MutexGuard deref_mut() .所以添加这一行就可以了:
    let state = state.deref_mut();

最佳答案

只是为了详细说明@Netwave 的回答,以防万一没有 Mutex你不会得到这样的错误,因为这样做

let mut state = State {
h1: HashMap::new(),
h2: HashMap::new(),
};
let v1 = state.h1.get_mut("abc").unwrap();
let v2 = state.h2.get_mut("abc").unwrap();
v1可变借用 state.h1 , 和 v2可变借用 state.h2 ,并且它们都算作 state 的不可变借用为了防止移动 state out(例如 let state2 = state; 而其他借用存在)。由于满足所有借用规则(每个对象至多一个可变借用或每个对象尽可能多的不可变借用),因此允许借用。
Mutex案例这一行
let mut state = state.lock().unwrap();
使 state类型 MutexGuard::<State> .通过这种方式使用它
let v1 = state.h1.get_mut("abc").unwrap();
Rust 找不到 h1MutexGuard::<State> ,这就是为什么它会使用 DerefMut获得的特质 &mut State隐含从它。这就是你可变借用的地方 state .因为您后来对 v2 使用了类似的结构。 ,您将尝试在 state 上获得第二个可变借用,从而收到错误

关于rust - Mutex 中的可变借用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68996216/

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