1

Is it possible to specify a global constant for a struct like a time::Duration?

const DELAY_TIME: time::Duration = ???
...
thread::sleep(DELAY_TIME);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Frank P
  • 455
  • 3
  • 7
  • I think because the fields of the `Duration` struct are private, you cannot use its constructor, and thus cannot use it as part of a `const` expression. – turbulencetoo Oct 23 '17 at 19:58
  • trying to use `Duration::new` yields this error: `error[E0015]: calls in constants are limited to struct and enum constructors` – turbulencetoo Oct 23 '17 at 19:59

1 Answers1

0

A Duration cannot be computed at compile-time, so you have two options:

  • Store the parameters to the constructor (easy, since they are just a u64 and a u32)
  • Store the Duration in a lazy_static (Requires dynamic allocation, atomic locking, and a dependent crate. Not recommended here).

Here's how to do the first option:

use std::time::Duration;
use std::thread::sleep;

const DELAY_SECONDS: u64 = 1;
const DELAY_NANO_SECONDS: u32 = 0;

fn main() {
    sleep(Duration::new(DELAY_SECONDS, DELAY_NANO_SECONDS));
}
Sean Pianka
  • 2,157
  • 2
  • 27
  • 43
Timidger
  • 1,199
  • 11
  • 15