Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: Error[E0277]: the trait bound `{integer}: SampleRange<_>` is not satisfied

Tags:

rust

I have a line of code that is in a for loop, and it's supposed to generate a random number from 0 to 2499. It is giving me problems.

let index = rand::thread_rng().gen_range(2499);

Full code for those who want to know:

fn generate_phrase () -> String {
let mut phrase = String::new();
let mut file = File::open("words.txt").expect("Failed to open words.txt");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Failed to read words.txt");
let words: Vec<&str> = contents.split("\n").collect();
for _ in 0..8 {
    let index = rand::thread_rng().gen_range(2499);
    phrase.push_str(words[index]);
    phrase.push(' ');
}
println!("Your phrase is: {:?}", phrase);
return phrase;
}

Error message:

error[E0277]: the trait bound `{integer}: SampleRange<_>` is not satisfied
   --> src/crypto/crypto.rs:115:45
    |
115 |    let index = rand::thread_rng().gen_range(2499);
    |                                   --------- ^^^^ the trait `SampleRange<_>` is not implemented for `{integer}`
    |                                   |
    |                                   required by a bound introduced by this call
    |
note: required by a bound in `gen_range`
   --> C:\Users\Administrator\.cargo\registry\src\github.com-1ecc6299db9ec823\rand-0.8.5\src\rng.rs:132:12
    |
132 |         R: SampleRange<T>
    |            ^^^^^^^^^^^^^^ required by this bound in `gen_range

I know the problem, which is that the trait is not the right kind but I don't know how to convert the integer into the necessary trait: SampleRange<T>. I've looked on StackOverFlow and couldn't find an appropriate answer anywhere.


1 Answers

The SampleRange that it complains about can be either a Range or RangeInclusive, rather than just an upper-bound (see the "implementations" section in SampleRange to see which types implement the trait). All you need is to change that one line to look something like this:

let index = rand::thread_rng().gen_range(0..2499);
like image 71
Jeremy Meadows Avatar answered Oct 26 '25 09:10

Jeremy Meadows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!