在 Rust 中,我试图找到一种方法来安全地设置全局Instant
. Instant
可能是单例的一种独特形式,因为它无法通过常量函数调用来初始化自己。尝试初始化static Instant
通孔会Instant::now()
导致以下错误:
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> src/main.rs:45:24
|
45 | static EPOCH:Instant = Instant::now();
|
^^^^^^^^^^^^^^
因此,我正在寻找一种理想的安全方法来执行上述操作。对于上下文,我已经有办法使用unsafe
rust来做到这一点:
use std::time::{Instant};
use std::mem::{self, MaybeUninit};
static mut MONOTONIC_EPOCH:MaybeUninit<Instant> = MaybeUninit::<Instant>::uninit();
fn set_epoch() {
unsafe {
MONOTONIC_EPOCH.as_mut_ptr().write(Instant::now());
}
}
在我的用例中,我需要全局单调时间点,可用于跟踪自程序执行中的某个时间点以来的时间。因此,全局Instant
在第一次设置后不需要是可变的。可以假设这种初始化在用例中可以保证在只有一个线程处于活动状态时发生。
注意:我确实需要一种方法来控制何时发生初始化Instant
。
您可以根据需要使用任何一个或多个版本:once_cell
::Lazy
sync
unsync
use std::time::{Instant};
use once_cell::sync::Lazy;
static EPOCH: Lazy<Instant> = Lazy::new(Instant::now);
如果要处理初始化完成的时间和地点,请OnceCell
改用:
use std::time::{Instant};
use once_cell::sync::OnceCell;
static EPOCH: OnceCell<Instant> = OnceCell::new();
fn main() {
let instant = EPOCH.get_or_init(Instant::now);
println!("{:?}", *instant);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句