generate a random number between 1 and 10 in rust

Here is an example code snippet to generate a random number between 1 and 10 in Rust using the built-in rand crate:

main.rs
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_number = rng.gen_range(1..=10);
    println!("Random number between 1 and 10: {}", random_number);
}
182 chars
8 lines

Explanation:

  • The rand::Rng trait provides methods for generating random numbers.
  • rand::thread_rng() creates a random number generator that is seeded from the operating system's entropy.
  • rng.gen_range(1..=10) generates a random number between 1 and 10 (inclusive on both ends).
  • The generated random number is then printed to the console using println! macro.

gistlibby LogSnag