Hello, again for some persons
I'm working on a little daemon which must deal with a web server game. This daemon must play non players characters in the following way: Non players characters will emit action at defined intervals. Daemon will create websocket (one par area in game world) and transmit websocket messages to concerned non players characters.
To deal with mutable constraints, I image to do this: Non players characters will emit actions without modify themselves (immutable). Part which receive with websocket messages will modify non players characters (mutable.)
There is a sample code:
Cargo.toml
[dependencies]
futures = "0.3.8"
[dependencies.async-std]
version = "1.8.0"
features = ["unstable"]
main.rs
use async_std::task;
use async_std::prelude::*;
use std::time::Duration;
use async_std::stream;
struct NonPlayableCharacter {
counter: i64,
}
impl NonPlayableCharacter {
pub async fn do_some_actions(&self) {
let mut interval = stream::interval(Duration::from_secs(1));
while let Some(_) = interval.next().await {
println!("emit {}", self.counter)
}
}
pub async fn react_to_event(&mut self) {
println!("work as mutable")
}
}
async fn daemon() {
let mut non_playable_characters = vec![
NonPlayableCharacter { counter: 0 },
NonPlayableCharacter { counter: 1000 },
];
let mut futures = futures::stream::FuturesUnordered::new();
// Add futures
futures.extend(non_playable_characters.iter().map(|npc| npc.do_some_actions()));
// Simulate two different websocket which receive messages (one websocket per area in world)
for i in 0..2 {
let mut npc = &mut non_playable_characters[i]; // for this example, a npc per websocket
npc.react_to_event(); // modify struct in react to websocket messages
}
futures.for_each(drop).await;
}
fn main() {
task::block_on(daemon())
}
But I can't use both mutable and immutable at once:
error[E0502]: cannot borrow `non_playable_characters` as mutable because it is also borrowed as immutable
--> src/main.rs:35:28
|
31 | futures.extend(non_playable_characters.iter().map(|npc| npc.do_some_actions()));
| ----------------------- immutable borrow occurs here
...
35 | let mut npc = &mut non_playable_characters[i];
| ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
...
39 | futures.for_each(drop).await;
| ------- immutable borrow later used here
How can I achieve my goal with immutable/mutable/borrow mechanism ? Note non player character state must be shared between "interval actions" and "websocket message react".