# Solved: random number in range

Random numbers are ubiquitous in programming. They are used in games, cryptography, simulations and much more. The generation of random numbers in programming is usually pseudo-random, as it’s generated with a deterministic initial value. One of the algorithms used to generate these numbers in Rust, a systems programming language, is the Mersenne Twister.

## Generating Random Numbers in Rust

Rust has a dedicated library crate for random number generation, namely, `rand`. If you want to generate a random number within a range, the ‘Rng’ trait provides a method ‘gen_range’ which is extremely handy.

Here’s how you can generate a random number between 1 and 100:

use rand::Rng;

fn main(){
println!(“Random number: {}”, num);
}

## Deep Dive into the Code

In the first line, we’re importing the ‘Rng’ trait from the ‘rand’ crate. It provides the methods necessary to generate random numbers.

The ‘main’ function is where we create a random number:

rand::thread_rng() is a convenient function that initializes an instance of the default random number generator of Rust and automatically determines a reasonably unpredictable seed.

).gen_range(1, 101); is the function call that generates the random number. You pass the range to this function in which you want your number to be.

Finally, the generated number is printed.

‘dyn’ keyword in Rust is used for dynamic dispatch. Dynamic dispatch allows us to have different types from the same trait.

The ‘rand’ crate also provides a functionality to generate random numbers within a range with multiple data types.

use rand::Rng;
fn main(){
let range = 0..8;