Rust Random Number Generation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Rust has a built in capability to provide random number generation through the rand crate. Once part of the Rust standard library, the functionality of the rand crate was separated to allow its development to stabilize separate to the rest of the Rust project. This topic will cover how to simply add the rand crate, then generate and output a random number in Rust.

Remarks

There is built-in support for a RNG associated with each thread stored in thread-local storage. This RNG can be accessed via thread_rng, or used implicitly via random. This RNG is normally randomly seeded from an operating-system source of randomness, e.g. /dev/urandom on Unix systems, and will automatically reseed itself from this source after generating 32 KiB of random data.

An application that requires an entropy source for cryptographic purposes must use OsRng, which reads randomness from the source that the operating system provides (e.g. /dev/urandom on Unixes or CryptGenRandom() on Windows). The other random number generators provided by this module are not suitable for such purposes.



Got any Rust Question?