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?
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);
}
A search for generating secure random numbers on Rust returned this SO question, but as a comment on the current answer states, Rust no longer includes random number generation in the standard library. Here's an updated example (as of Jan. 2017):
[dependencies]
rand = "0.3.0"
extern crate rand;
use rand::{OsRng, Rng};
fn main() {
let mut rng = OsRng::new().expect("Error opening random number generator");
println!("Random: {}", rng.next_u32());
}
Useful reference: https://doc.rust-lang.org/rand/rand/index.html#cryptographic-security
Otherwise, using the code from the original answer gives this error:
error[E0432]: unresolved import `std::rand::Rng`
--> src/main.rs:5:24
|
5 | use std::rand::{OsRng, Rng};
| ^^^ no `Rng` in `std::rand`
error: module `rand` is private
--> src/main.rs:5:17
|
5 | use std::rand::{OsRng, Rng};
| ^^^^^
error: module `rand` is private
--> src/main.rs:5:24
|
5 | use std::rand::{OsRng, Rng};
| ^^^
error: aborting due to 3 previous errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With