I have a function that is supposed to pick random words from a list of words:
pub fn random_words<'a, I, R>(rng: &mut R, n: usize, words: I) -> Vec<&'a str>
where
I: IntoIterator<Item = &'a str>,
R: rand::Rng,
{
rand::sample(rng, words.into_iter(), n)
}
Presumably that's a reasonable signature: Since I don't actually need the string itself in the function, working on references is more efficient than taking a full String
.
How do I elegantly and efficiently pass a Vec<String>
with words that my program reads from a file to this function? I got as far as this:
extern crate rand;
fn main() {
let mut rng = rand::thread_rng();
let wordlist: Vec<String> = vec!["a".to_string(), "b".to_string()];
let words = random_words(&mut rng, 4, wordlist.iter().map(|s| s.as_ref()));
}
Is that the proper way? Can I write this without explicitly mapping over the list of words to get a reference?