Random Number Generator in Rust

To generate a random number in Rust, you typically use the rand crate, which is a popular choice for random number generation. First, ensure you have the rand crate included in your Cargo.toml file:


                                
                // cargo.toml
                [dependencies]
                rand = "0.8.4"
                
                // the code:
                use rand::Rng; // Rng trait defines methods for random number generation
                
                fn main() {
                    let mut rng = rand::thread_rng(); // Get a random number generator
                    let random_number: i32 = rng.gen_range(1..=10); // Generate a random number between 1 and 10, inclusive
                    println!("Random number: {}", random_number);
                }
                
                

In this example:

Preset number shortcuts between

Digit shortcuts

Code samples