Search code examples
rustrust-cargo

Trying to create random number to const


I'm trying to create a random number to const value using const_random and get the same value

I have the following code:

use const_random::const_random;


pub mod random_id{
    const NUMBER: u64 = const_random!(u64)
     
    pub fn get_number() - > u64 {
        return NUMBER;
    }
}

I got always the same number, how can I fix it?


Solution

  • Is this the kind of thing you're looking for?

    use std::sync::OnceLock;
    
    use rand; // 0.8.5
    
    fn the_random_value() -> u64 {
        // A `static` value is shared and reused whenever you call the
        // function, and this `OnceLock::new()` will only be called once,
        // when the program starts.
        static RANDOM: OnceLock<u64> = OnceLock::new();
    
        // `OnceLock::get_or_init` is designed to be called only once,
        // when you reach this line for the first time.
        *RANDOM.get_or_init(rand::random)
    }
    
    fn main() {
        // This will print several times the same value,
        // but a different value upon each startup.
        println!("RANDOM: {}", the_random_value());
        println!("RANDOM: {}", the_random_value());
        println!("RANDOM: {}", the_random_value());
        println!("RANDOM: {}", the_random_value());
        println!("RANDOM: {}", the_random_value());
    }
    

    (another version, which uses the now mostly deprecated lazy_static)

    use lazy_static::lazy_static; // 1.4.0
    use rand; // 0.8.5
    
    
    lazy_static!{
        // On the first call, this produces a random value.
        // Subsequent calls will reuse the same value.
        // Value is refreshed upon each start of the program.
        static ref RANDOM : u64 = rand::random();
    }
    
    fn main() {
        // This will print several times the same value,
        // but a different value upon each startup.
        println!("RANDOM: {}", *RANDOM);
        println!("RANDOM: {}", *RANDOM);
        println!("RANDOM: {}", *RANDOM);
        println!("RANDOM: {}", *RANDOM);
        println!("RANDOM: {}", *RANDOM);
    }