Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random u8 from 0 to 255 inclusively

Tags:

random

rust

I am trying to make a program that generates random numbers from 0 to 255 inclusively. It seems so simple! I did this:

extern crate rand;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen_range(0, 255);

    println!("Your random number is {}", random_number);
}

This works fine, but the problem with this approach is that the number 255 will not be included:

The gen_range method takes two numbers as arguments and generates a random number between them. It’s inclusive on the lower bound but exclusive on the upper bound.

When I try to do this :

let random_number: u8 = rand::thread_rng().gen_range(0, 256);

Rust will generate a warning because u8 only accepts values from 0 to 255.

warning: literal out of range for u8
 --> src/main.rs:6:61
  |
6 |     let random_number: u8 = rand::thread_rng().gen_range(0, 256);
  |                                                             ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

How do I work around this without having to change the type of the random_number variable?

like image 781
Rain Avatar asked Dec 09 '17 00:12

Rain


1 Answers

Use the gen method instead. This method will generate a random value from the whole set of possible values for the specified type.

extern crate rand;

use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen();

    println!("Your random number is {}", random_number);
}
like image 139
Francis Gagné Avatar answered Oct 23 '22 12:10

Francis Gagné