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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With