在Rust中同时访问全局哈希映射中的两个可变引用



假设我们有一个全局可访问的特征对象哈希图,我们用lazy_static:MY_ANIMALS: Mutex<HashMap<i32, AnimalBox>>,其中type AnimalBox = Box<dyn AnimalExt+Send>

现在,我们希望这个全球主题地图中的动物能够相互交流。例如,一个AnimalBox可以AnimalExt::eat(&mut self, prey: &mut AnimalBox)另一个。

问题是,我们的eat()函数既需要对self的可变引用,也需要对pray的可变引用(因为我们希望pray在被吃掉时指向AnimalExt::perish(&mut self)

然而,获得对哈希图的两个可变引用会导致WouldBlock错误:

use lazy_static::lazy_static;
use std::sync::Mutex;
use std::collections::HashMap;
//type alias for our boxed animals
type AnimalBox = Box<dyn AnimalExt+Send>;
//globally accessible hashmap for keeping track of our animals throughout the scope of our application
lazy_static! {
static ref MY_ANIMALS: Mutex<HashMap<i32, AnimalBox>> = Mutex::new(HashMap::new());
}
//simple trait for our animals
trait AnimalExt{
//eat() function requires a mutable reference to another AnimalBox
fn eat(&mut self, pray: &mut AnimalBox);
fn perish(&mut self);
fn energy(&self)->i32;
fn id(&self)->i32;
}
struct Wolf{
id: i32,
energy: i32,
alive: bool,
}
impl AnimalExt for Wolf{
fn id(&self)->i32{
self.id
}
fn eat(&mut self, pray: &mut AnimalBox) {
pray.perish();
self.energy+= pray.energy()
}
fn energy(&self) ->i32 {
self.energy
}
fn perish(&mut self){
self.alive = false; 
}
}
impl Wolf{
pub fn new(id: i32)->Self{
Wolf{
id: id,
energy: 50,
alive: true,
}
}
}
struct Cow{
id: i32,
energy: i32,
alive: bool,
}
impl Cow{
pub fn new(id: i32)->Self{
Cow{
id: id,
energy: 100,
alive: true,
}
}
}
impl AnimalExt for Cow{
fn id(&self)->i32{
self.id
}
fn eat(&mut self, pray: &mut AnimalBox) {
pray.perish();
self.energy+= pray.energy()
}
fn energy(&self) ->i32 {
self.energy
}
fn perish(&mut self){
self.alive = false; 
}
}
fn main() {
println!("Hello, world!");
//define our animals
let cow1 = Box::new(Cow::new(1)) as AnimalBox;
let cow2 = Box::new(Cow::new(2)) as AnimalBox;
let wolf1 = Box::new(Wolf::new(3)) as AnimalBox;
let wolf2 = Box::new(Wolf::new(4)) as AnimalBox;
//insert them into the global hashmap
MY_ANIMALS.lock().unwrap().insert(cow1.id(), cow1);
MY_ANIMALS.lock().unwrap().insert(cow2.id(), cow2);
MY_ANIMALS.lock().unwrap().insert(wolf1.id(), wolf1);
MY_ANIMALS.lock().unwrap().insert(wolf2.id(), wolf2);
//getting one animal to eat() another causes a WouldBlock error
match (MY_ANIMALS.try_lock().unwrap().get_mut(&0), MY_ANIMALS.try_lock().unwrap().get_mut(&1)){
(Some(a1), Some(a2))=>{
a1.eat(a2);
}
_=>()
}
}

这方面有什么好办法吗?或者没有一种安全的方法可以用hashmap来实现这一点吗?我看到过类似问题的答案,但建议的答案建议使用RefCell,这与lazy_static的Send特性要求不兼容。

我最终使用了muti_mut板条箱,它提供了几种方法来对HashMap或BTreeMap进行多个可变引用。

use lazy_static::lazy_static;
use std::sync::Mutex;
use std::collections::HashMap;
use multi_mut::{HashMapMultiMut, HashMapMutWrapper};
//type alias for our boxed animals
type AnimalBox = Box<dyn AnimalExt+Send>;
//globally accessible Hashmap for keeping track of our animals throughout the scope of our application
lazy_static! {
static ref MY_ANIMALS: Mutex<HashMap<i32, AnimalBox>> = Mutex::new(HashMap::new());
}
//simple trait
trait AnimalExt{
//eat() function requires a mutable reference to another AnimalBox
fn eat(&mut self, pray: &mut AnimalBox);
fn perish(&mut self);
fn energy(&self)->i32;
fn id(&self)->i32;
}
struct Wolf{
id: i32,
energy: i32,
alive: bool,
}
impl AnimalExt for Wolf{
fn id(&self)->i32{
self.id
}
fn eat(&mut self, pray: &mut AnimalBox) {
pray.perish();
self.energy+= pray.energy()
}
fn energy(&self) ->i32 {
self.energy
}
fn perish(&mut self){
self.alive = false; 
}
}
impl Wolf{
pub fn new(id: i32)->Self{
Wolf{
id: id,
energy: 50,
alive: true,
}
}
}
struct Cow{
id: i32,
energy: i32,
alive: bool,
}
impl Cow{
pub fn new(id: i32)->Self{
Cow{
id: id,
energy: 100,
alive: true,
}
}
}
impl AnimalExt for Cow{
fn id(&self)->i32{
self.id
}
fn eat(&mut self, pray: &mut AnimalBox) {
pray.perish();
self.energy+= pray.energy()
}
fn energy(&self) ->i32 {
self.energy
}
fn perish(&mut self){
self.alive = false; 
}
}
fn main() {
println!("Hello, world!");
//define our animals
let cow1 = Box::new(Cow::new(1)) as AnimalBox;
let wolf1 = Box::new(Wolf::new(2)) as AnimalBox;
let before_eating_cow = wolf1.energy();
//insert them into the global hashmap
MY_ANIMALS.lock().unwrap().insert(cow1.id(), cow1);
MY_ANIMALS.lock().unwrap().insert(wolf1.id(), wolf1);

//use get_pair_mut method from the multi_mut crate
match MY_ANIMALS.try_lock().unwrap().get_pair_mut(&1, &2){
Some((hunter, prey))=>{
dbg!("hunter eats prey");
hunter.eat(prey);
}
None=>()
}
let after_eating_cow = MY_ANIMALS.lock().unwrap().get(&1).unwrap().energy();
assert_ne!(before_eating_cow, after_eating_cow);
}

最新更新