I am trying to create a program that generates random numbers from 0 to 255 inclusive. It seems so simple! I have done 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 great, but the problem with this approach is that the number 255 will not be included :
The method gen_rangetakes two numbers as arguments and generates a random number between them. It is inclusive on the lower border, but exclusively on the upper border.
When I try to do this:
let random_number: u8 = rand::thread_rng().gen_range(0, 256);
Rust will generate a warning because it u8accepts 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 can I get around this without changing the type of the variable random_number?
source
share