Reputation: 241
I'm looking for something like this (below is C)
void MyFunction() {
//Do work
static int serial;
++serial;
printf("Function run #%d\n", serial);
//Do more work
}
Upvotes: 0
Views: 336
Reputation: 40814
As Ice Giant mentions in their answer, you can use static mut
to solve this. However, it is unsafe for a good reason: if you use it, you are responsible for making sure that the code is thread safe.
It's very easy to misuse and introduce unsound code and undefined behavior into your Rust program, so what I would recommend that you do instead is to use a type that provides safe interior mutability, such as Mutex
, RwLock
, or in the case of integers, atomics like AtomicU32
:
use std::sync::atomic::{AtomicU32, Ordering};
fn my_function() {
// NOTE: AtomicU32 has safe interior mutability, so we don't need `mut` here
static SERIAL: AtomicU32 = AtomicU32::new(0);
// fetch and increment SERIAL in a single atomic operation
let serial = SERIAL.fetch_add(1, Ordering::Relaxed);
// do something with `serial`...
println!("function run #{}", serial);
}
Because this program does not contain any unsafe code, we can be certain that the program does not contain the same data race bugs that can be caused by naïve use of static mut
(or the equivalent use of static
in the C code).
Upvotes: 7