use std::time::Instant;
use std::collections::HashMap;
use core::cell::RefCell;
struct Focus(/*start*/ Instant, /*end*/ Instant);
#[derive(Default)]
struct Session {
pid: u32,
had_focus: Vec<Focus>,
run_time: u64,
}
#[derive(Default)]
struct Game {
name: String,
focus_time_total: u64,
focus_time_7_days: u64,
run_time_total: u64,
run_time_7_days: u64,
sessions: RefCell<Vec<Session>>,
}
fn main() {
let mut games: HashMap<String, Game> = HashMap::new();
// ...
let name = "some game";
let pid = 123;
if !games.contains_key(name) {
let g = Game {
name: name.to_string(),
focus_time_total: 0,
focus_time_7_days: 0,
run_time_total: 0,
run_time_7_days: 0,
sessions: Default::default(),
};
games.insert(name.to_string(), g);
}
// if there's no session for this pid, create one, then update the session info
let mut sessions = games.get(name).unwrap().sessions.borrow_mut();
let last_session = sessions.last();
if last_session.is_none() || last_session.unwrap().pid != pid {
let session = Session {
pid: pid,
had_focus: vec![Focus(Instant::now(), Instant::now())],
run_time: 0,
};
sessions.push(session);
}
let mut current_session = &mut sessions.last().unwrap();
current_session.run_time = 123; // breaks
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0594]: cannot assign to `current_session.run_time`, which is behind a `&` reference
--> src/main.rs:60:5
|
60 | current_session.run_time = 123;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign
For more information about this error, try `rustc --explain E0594`.
error: could not compile `playground` due to previous error
I'm new to Rust and have been struggling to get struct vector fields to do what I want them to do. I have a struct, Game
with a vector of Sessions
. I want to push a Session
if one doesn't exist and update one if it does exist.
The use of RefCell
on Game::sessions
also feels wrong to me for some reason. I feel like I'm trying to force Rust to operate under the paradigms I'm used to instead of doing things the "Rust way".
Any help?
Many thanks in advance.