[][src]Trait rand::FromEntropy

pub trait FromEntropy: SeedableRng {
    fn from_entropy() -> Self;

A convenience extension to SeedableRng allowing construction from fresh entropy. This trait is automatically implemented for any PRNG implementing SeedableRng and is not intended to be implemented by users.

This is equivalent to using SeedableRng::from_rng(EntropyRng::new()) then unwrapping the result.

Since this is convenient and secure, it is the recommended way to create PRNGs, though two alternatives may be considered:

  • Deterministic creation using SeedableRng::from_seed with a fixed seed
  • Seeding from thread_rng: SeedableRng::from_rng(thread_rng())?; this will usually be faster and should also be secure, but requires trusting one extra component.


use rand::{Rng, FromEntropy};
use rand::rngs::StdRng;

let mut rng = StdRng::from_entropy();
println!("Random die roll: {}", rng.gen_range(1, 7));

Required methods

fn from_entropy() -> Self

Creates a new instance, automatically seeded with fresh entropy.

Normally this will use OsRng, but if that fails JitterRng will be used instead. Both should be suitable for cryptography. It is possible that both entropy sources will fail though unlikely; failures would almost certainly be platform limitations or build issues, i.e. most applications targetting PC/mobile platforms should not need to worry about this failing.


If all entropy sources fail this will panic. If you need to handle errors, use the following code, equivalent aside from error handling:

use rand::prelude::*;
use rand::rngs::EntropyRng;

// This uses StdRng, but is valid for any R: SeedableRng
let mut rng = StdRng::from_rng(EntropyRng::new())?;

println!("random number: {}", rng.gen_range(1, 10));
Loading content...


impl<R: SeedableRng> FromEntropy for R

Loading content...