简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM