[英]Access two mutable references from a Global hashmap at once in Rust
假設我們有一個全局可訪問的 trait 對象哈希圖,我們使用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 的可變引用(因為我們希望在它被吃掉時向AnimalExt::perish(&mut self)
發送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);
}
_=>()
}
}
有沒有好的解決方法? 或者有沒有安全的方法可以用哈希圖來做到這一點? 我已經看到了類似問題的這個答案,但建議的答案建議使用RefCell
,這與lazy_static 的Send
特征要求不兼容。
我最終使用了muti_mut crate,它提供了多種方法來對 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.