user19316228
user19316228

Reputation:

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

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.

Upvotes: 4

Views: 2333

Answers (1)

Jeremy Meadows
Jeremy Meadows

Reputation: 2561

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);

Upvotes: 9

Related Questions