I'm trying to create a bunch of structs and have each know its place in the order of creation but struggling to do so without an unsafe block. I'm learning (very early in the process) so want to learn how to avoid unsafe code.
struct LogMonitor {
logfile: String,
index: usize,
}
static mut next_monitor: usize = 0;
impl LogMonitor {
pub fn new(f: String) -> LogMonitor {
let index = next_monitor;
next_monitor += 1;
LogMonitor {
logfile: f,
index,
}
}
}
The above gives an error at let index = next_monitor;
which says use of static requires an unsafe function or block, because it could be mutated in multiple threads.
I then tried thread_local
as below but can't get this to work either. I can't make NEXTMON mutable, so the *i = *i + 1;
is an error.
I'm very new to Rust so any help is very userful. Thanks.
thread_local! {
static NEXTMON: usize = 0;
}
impl LogMonitor {
pub fn new(f: String) -> LogMonitor {
NEXTMON.with(|i| {
let index = i;
*i = *i + 1;
index;
});
LogMonitor {
logfile: f,
index: 1
}
}
}
Whats a good way to do this without writing unsafe code?