The Wayback Machine - https://web.archive.org/web/20240915215500/https://www.geeksforgeeks.org/how-to-generate-random-numbers-in-rust-language/
Open In App

How to Generate Random Numbers in Rust Language?

Last Updated : 28 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Random number generation is an important feature in programming to design complex and automated programs. We can generate random numbers in rust with the help of the rand crate.

Generate a Random Number:

We will use the rand crate and the Rng trait in Rust that gives us access to certain functions that help us in generating random numbers.  Inside the main function, we can then create a mutable rng variable which we will assign as a random number generator that is needed by the system (random value from which the thread will assign numbers). Using the rng thread, we can generate a random number appropriate to the limit of the variable assigned. 

Using the gen function which returns the number within the bounds of the variable type in this vase u8, the number returned is given out by a standard distribution. 

 

We can even generate random numbers beyond the 8-bit like, u16, u32, u64, u128, or even signed integers with i8, i16, i32, i64, and i128. 

Generate Random Numbers within a Range:

We can also generate random numbers with a specified range. We use the gen_range function to get a random number by uniform distribution between the two limits passed as its parameter. To demonstrate this, we run a for loop and print the number generated from the gen_range function in each iteration. 

rng.gen_range(0..10)

The upper bound is non-inclusive so the number 10 won’t be generated from the function. However, we can make it inclusive by adding the = operator before the upper bound.

rng.gen_range(0..=10)

Example 1:

Rust




// RUST code: Generate Random Numbers within a Range
use rand::Rng;
  
fn main() {
    let mut rng = rand::thread_rng();
      
    for _x in 0..5{
    let num: u8 = rng.gen_range(0..10);
    println!("Random number between 0 and 9: {}", num);
    }
}


Output:

 

 

Example 2:

Rust




// RUST Code: Using the inclusive range 
// for generating random numbers
use rand::Rng;
  
fn main() {
    let mut rng = rand::thread_rng();
      
    for _x in 0..5{
    let num: u8 = rng.gen_range(0..=10);
    println!("Random number : {}", num);
    }
}


Output:

 

In this example, we were able to generate random numbers within a given range both inclusive and non-inclusive upper bound.

Generate Random Boolean:

We can even generate random boolean values with a species distribution of the probabilities of true and false. Using the gen_bool function and passing the distribution as a fraction to it we get a boolean value from the function.

Example 3:

Rust




// RUST Code: Generating random boolean value
use rand::Rng;
  
fn main() {
    let mut rng = rand::thread_rng();
      
    for _x in 0..5{
    let toss: bool = rng.gen_bool(0.5);
    println!("Random number : {}", toss);
    }
}


Output:

 

As we have given a parameter of 0.5 it will generate the boolean values evenly, if we give the distribution as 1, it will only print true as the probability of false or other event becomes 0. 

Thus,  we were able to generate random numbers in Rust using the rand create with gen, gen_range, and gen_bool methods to generate numbers in different distributions. 



Similar Reads

Rust vs C++ - Will Rust Replace C++ in Future
We have seen many programming languages trending according to their functionality and popularity but languages are not meant to be used according to their popularity. We should consider the overall efficiency and productivity when it comes to using a programming language. Speaking of efficiency and popularity one of the most used programming langua
6 min read
Introduction to Rust Programming Language
Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory-safety and thread-safety, empowering developers to debug at compile-time. In addition to that Rust has great documentation and a user-friendly compiler with
8 min read
Rust: The Programming Language of the Future?
In the ever-changing landscape of programming languages, Rust has positioned itself as a strong candidate to be crowned “Programming Language of the Future.” Developed by Mozilla in 2006 and currently maintained by the Rust Foundation, Rust has drawn significant attention and uptake due to its unique combination of performance, safety, and modern s
7 min read
Rust - Bounds
In Rust, we have a concept of Bounds. Bounds are used in situations when we are working with generics and are trying to figure out the nature and type of parameters that are required for stipulating the functionality that the type in Rust implements. Syntax: fn gfg <T: GeeksforGeeks>(x: T) { println!(" {}", x); //more methods defined} In the
2 min read
Rust lifetime Constructor
In Rust, we have a concept of a lifetime constructor that falls under the ownership category. Rust enforces a certain set of rules through its concept of ownership and lifetimes. In this article, we would be learning more about Lifetimes in Rust. In Rust, there are various regions that are present in the code which are generally complex and referre
3 min read
Rust - Casting
Type Conversion or casting in Rust is a way to convert one type to another. As its name suggests, type conversion is the process of converting variables from one data type to another. So that, the compiler treats the variable as a new datatype. Rust doesn't allow us to implicitly convert the datatype between primitive types. The primitive types are
3 min read
Rust - Struct Visibility
In Rust, there is a concept of Struct Visibility. Generally, the items present in the module have visibility that is private by nature but we can override the private items by usage of the public ('pub') modifier. Public items of the module are accessed outside the module scope and the visibility in these scenarios is not very high. To avoid this s
3 min read
Rust - If let Operator
The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it. Syntax : let gfg=value; let gfg_answer=if let value_1
2 min read
Rust - Reference Counted Smart Pointer
In Rust, there is a concept of a Smart pointer where we use multiple ownership explicitly using the Rc<T> type. This Rc <type> is referred to as Reference counting. This concept was introduced in Rust to handle scenarios where a single value of the variable has multiple owners. Rc<T> keeps how many references are made to a value a
2 min read
Rust - A Case of Safe Concurrency
Before looking at Rust itself, let's go back to 1992. Guido van Rossum, in an attempt to tackle race condition in CPython interpreter, added a lock famously known as the Global Interpreter Lock or GIL for short. Two and a half decades later, this was one of the main shortcomings for the Python interpreter we all love and use. So what is the Global
5 min read
Rust - Crate_type Attribute
In Rust, we have a concept of crates. Crates are basically libraries or packages as defined in other programming languages. Cargo, the rust package management tool helps ship the crates of our program to other programs' cargo. Crates produce an executable library where every crate has a root module that has the code for the crate. The crate_type at
2 min read
Rust Basics
In the last 2 decades, computers and the internet have made an increasing demand, and with the evolution of new technologies, devices, and protocols the programming languages are also being updated regularly but still most of the early programming languages like C, and C++ have shown some drawbacks. These drawbacks motivated others to create new pr
5 min read
Standard I/O in Rust
In this article, we will explore the standard input and standard output in the Rust programming language. Generally, the standard input is provided through the keyboard and the standard output displays values in the console. There are two core traits in Rust, around which the Rust's standard Input and Output are featured. They provide an interface
4 min read
Functions in Rust
Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the "fn" keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style
4 min read
Conditionals in Rust
Conditional Statements are the decision-making statements based on given conditions. Conditional statements are common in programming languages and rust has them and unlike many of them, the boolean condition doesn't need to be surrounded by parentheses but is better to use, and each condition is followed by a block. Some things to keep in mind whi
3 min read
Variables in Rust
Variables are memory addresses used to store information to be referenced and manipulated in programs. They also provide a way of defining data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label a
4 min read
Primitive Compound Datatypes in Rust
Rust programming language has a concept of compound data types which collections that can group multiple types into one. In simple words, compound Datatypes are data structures that can hold multiple data elements in a single variable (or) reference. There are two primitive compound types in Rust: ArraysTuplesThe Tuple Type: A tuple in Rust is a fi
2 min read
Rust - Operators
Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. In this article, we will look into different types of Rust operators. Operators tell the compiler or interpreter to perform a specific mathematical, logical, or relational operation. The
8 min read
Rust - Hello World Program
Every programmer starts their programming journey with a simple "Hello World!" program. In this article, we will write our first "Hello World!" Rust program. If you have not yet installed Rust on your system, please go through the link and install it. In this article we will be working on the following topics: Creating a Project Directory for the H
3 min read
Rust - Vectors
Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity. Vectors ensure they never allocate more than isize::MAX bytes. A simpl
4 min read
Rust - Slices
Slice is a data type that does not have ownership. Slice references a contiguous memory allocation rather than the whole collection. Slices are also present in Python which is similar to slice here in Rust. Slice is used when you do not want the complete collection, or you want some part of it. Slicing Key Points : In slicing first element is at 0
3 min read
Rust - HashMaps
The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated. 1. Insertion In HashMap : To insert a value in a HashMap in Rust follow the below steps: Import HashMapC
4 min read
Rust - Match Operator
Match Operator is a powerful operator which lets you match a particular value with a range of values and execute some operations or code for it. It is similar to switch() in Java. Match Operator Keypoints :For checking for a group of values, where the value to be checked is "cp".Syntax : let gfg = String::from("cp"); // match operator match &*g
3 min read
Rust - Tuple
A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop. Tuples in Rust are defined using small brackets as shown below :
2 min read
Rust - Unrecoverable Errors
Unrecoverable errors are those errors which as the name suggests can not be handled by a programmer. When any unrecoverable error occurs the end result is the program quits (terminates). The complete process is the first panic! macro is fired then the error message is printed along with the location of it and finally, the program is terminated. It
2 min read
How to Install Rust on Windows and Linux Operating System?
Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory-safety and thread-safety, empowering developers to debug at compile-time. In addition to that Rust has great documentation and a user-friendly compiler with
2 min read
Rust - Enum
An enum in Rust is a custom data type that represents data that can be anyone among several possible variants. Each variant in the enum can optionally have data associated with it. An enumerated type is defined using the enum keyword before the name of the enumeration. It also consists of methods. Syntax: enum name_of_enum{ variant_1, variant_2, .
3 min read
Rust - Constants
Constants are the value that can not be changed after assigning them. If we created a constant, then there is no way of changing its value. The keyword for declaring constant is const. In Rust, constants must be explicitly typed. The below syntax is used to initialize a constant value: Syntax : const VARIABLE_NAME:dataType = value; Now let's check
1 min read
Rust - Traits
A trait tells the Rust compiler about functionality a particular type has and can share with other types. Traits are an abstract definition of shared behavior amongst different types. So, we can say that traits are to Rust what interfaces are to Java or abstract classes are to C++. A trait method is able to access other methods within that trait. T
8 min read
Rust - Drop Trait
Drop trait lets us customize what happens when a value is about to go out of scope. Drop trait is important to the smart pointer pattern. Drop trait functionality is used when implementing a smart pointer. For example, Box<T> customizes Drop to deallocate the space on the heap that the box points to. Drop trait can be used to clean up values
3 min read
Article Tags :