Rust program to generate integer random numbers

Rust | Random Numbers Example: Write a program to generate integer random numbers.
Submitted by Nidhi, on November 12, 2021

Problem Solution:

In this program, we will generate 8-bit, 16-bit, 32-bit integer numbers using the gen() method and print the result.

Add random external library to your project

  1. Create your project using the below command.
    $cargo new random --bin
  2. Goto the project folder cd random and edit Cargo.toml file.
    $random>nano Cargo.toml
  3. Then add dependency in Cargo.toml file
    rand = "0.5.5"
  4. After that, build your project using the below command
    $random>cargo build
  5. Then execute your project after modification in the src/ source file.
    $random>cargo run

Program/Source Code:

The source code to generate integer random numbers is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to generate integer random numbers

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();

    let num8: u8   = rng.gen();
    let num16: u16 = rng.gen();
    let num32: u32 = rng.gen();
    println!("Random u8 : {}", num8 );
    println!("Random u16: {}", num16);
    println!("Random u32: {}", num32);


$random> cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/random`

Random u8 : 7
Random u16: 8397
Random u16: 1476775958


In the above program, we imported the "rand" library to our project for generating random numbers. We imported the "rand" library using the below line:

use rand::Rng;

In the main() function, we generated 8-bit, 16-bit, 32-bit unsigned integer numbers using the gen() method and printed the result.

Rust Random Numbers Programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.