Passing Vec <String> as IntoIterator <& 'a str>

I have a function that should select 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, a reasonable signature: since I really don't need the string itself in the function, working on links is more efficient than full String.

How can I elegantly and efficiently convey the Vec<String>words that my program reads from a file of this function? I got to 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 this the right way? Can I write this without explicit matching above a list of words to get a link?

+4
source share
1 answer

, , &str , , &str:

pub fn random_words<'a, I, R, J>(rng: &mut R, n: usize, words: I) -> Vec<&'a str>
where
    I: IntoIterator<Item = &'a J>,
    J: AsRef<str> + 'a,
    R: rand::Rng,
{
    rand::sample(rng, words.into_iter().map(AsRef::as_ref), n)
}
let words: Vec<&str> = random_words(&mut rng, 4, &wordlist);

,

+5

All Articles