time.Instant module level variable

I got error for the below, calls in statics are limited to constant functions, tuple structs and tuple variants

I have 2 questions:
1: how to declare module level Instant type variable?
2: as_millis() return u128, is it ok to do as u32 here?

use std::time::{Duration, Instant};
use std::thread::sleep;

static refTime: Instant = Instant::now();

fn currentMs() -> u32 {
    refTime.elapsed().as_millis() as u32

fn main() {
//   let now = Instant::now();

   sleep(Duration::new(2, 0));
   println!("{}", currentMs() );

Static variables are initialized at compile time. Their initial values are packed into the executable binary and loaded by the OS of the target machine.

You can use OnceCell<Instant> to initialize it on main() and use it elsewhere.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.