简体   繁体   English

将Vec <String>作为IntoIterator传递<&'a str>

[英]Passing Vec<String> as IntoIterator<&'a str>

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 . 大概这是一个合理的签名:因为我实际上并不需要函数中的字符串本身,所以处理引用比获取完整的String更有效。

How do I elegantly and efficiently pass a Vec<String> with words that my program reads from a file to this function? 如何优雅高效地将Vec<String>与我的程序从文件中读取的单词传递给此函数? 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? 我是否可以在没有明确映射单词列表的情况下编写此代码来获取引用?

You can change your generic function to take anything that can be turned into a &str instead of having it take an iterator that yields a &str : 你可以改变你的泛型函数,把任何可以变成&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);

The Book even has an entire chapter devoted to this topic 本书甚至有一整章专门讨论这个主题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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