Random number generation

I'm trying to generate random number using the following code and it works.

use rand::RngCore; //Traits are brought to scope to use functions.
use hex;

fn main()

    let mut r  = rand::thread_rng();

    //let i : f64 = r.RngCore::next_u32().expect("dd");
    let mut rand_buf : [u8;16] = [0;16];

    r.try_fill_bytes(& mut rand_buf);

    println!("{}", hex::encode(& rand_buf));


If I chage the statement

let mut r  = rand::thread_rng();

with type annotation

let mut r : rand::ThreadRng = rand::thread_rng();

The code does not compile. ThreadRng is a struct define in rand crate. thread_rng() is
defined in the rand crate and as per doc it returns ThreadRng.

Whats could be the reason?


ThreadRng is in a submodule, so you need to access it like so,

let mut r : rand::rngs::ThreadRng = rand::thread_rng();

Thanks a lot.
My eyes did not catch up when I browse rand docs.
Thanks again

What did the error message say?

Look at the error messages the compiler issues. There should be a suggestion what type might be right one.

Thanks....it was a namespace path issue. When I correctly
specified as
let mut r: rand::rngs::ThreadRng = rand::thread_rng();
it works.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.