Rust program to generate a random tuple

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

Problem Solution:

In this program, we will generate a random tuple that contains a 32-bit integer, Boolean value, and 64-bit float number.

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 a random tuple is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to generate a random tuple

use rand::Rng;
use rand::distributions::{Distribution, Standard};

fn main() {
    let mut rnd = rand::thread_rng();
    let myTuple = rnd.gen::<(i32, bool, f64)>();

    println!("Generated random tuple: {:?}", myTuple);


$random> cargo run
Compiling random v0.1.0 (/home/arvind/Desktop/rust/random)
    Finished dev [unoptimized + debuginfo] target(s) in 0.29s
     Running `target/debug/random`

Generated random tuple: (319921382, true, 0.8608721348875811)


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 a tuple using the gen() method and printed the result.

Rust Random Numbers Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.