传递Vec< String>作为IntoIterator<&'str> [英] Passing Vec<String> as IntoIterator<&'a str>

查看:153
本文介绍了传递Vec< String>作为IntoIterator<&'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.

如何优雅高效地将 Vec< 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?

推荐答案

您可以更改您的通用函数任何可以变成& str 的东西,而不是让它产生一个产生& str 的迭代器:

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:

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

本书甚至有一整章专门讨论这个话题

这篇关于传递Vec&lt; String&gt;作为IntoIterator&lt;&amp;'str&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆