Search code examples
randomrustrust-obsolete

Generating secure random numbers in Rust


I can see I have to import like this:

use std::io::IoResult;
use std::num::{Int, ToPrimitive};
use std::rand::{OsRng, Rng};

Then make a new instance of OsRng, and try to generate a new u32 int from it

fn main() {

  let mut rng = OsRng::new();

  let num:u32 = rng.next_u32();
  println!("{}",num);
}

However I get the error type core::result::Result<std::rand::os::imp::OsRng, std::io::IoError> does not implement any method in scope named next_u32

But the rust documentation clearly says there is a function next_u32? http://doc.rust-lang.org/std/rand/struct.OsRng.html

What am I missing?


Solution

  • Your problem here is that OsRng::new() does not return an OsRng instance, but an IoResult<OsRng>. Because the program can fail to fetch the OS random number generator.

    A sample use would be:

    use std::rand::{OsRng, Rng};
    
    fn main() {
    
        let mut rng = match OsRng::new() {
            Ok(g) => g,
            Err(e) => panic!("Failed to obtain OS RNG: {}", e)
        };
    
        let num:u32 = rng.next_u32();
        println!("{}",num);
    }