我试图筛选Vec<Vocabulary>这里Vocabulary是一个自定义的struct,它本身包含一个struct VocabularyMetadata和Vec<Word>:
#[derive(Serialize, Deserialize)]
pub struct Vocabulary {
pub metadata: VocabularyMetadata,
pub words: Vec<Word>
}
Run Code Online (Sandbox Code Playgroud)
这用于处理Web应用程序中的路由,其中路由如下所示:/word/<vocabulary_id>/<word_id>.
这里是我当前的代码试图filter在Vec<Vocabulary>:
let the_vocabulary: Vec<Vocabulary> = vocabulary_context.vocabularies.iter()
.filter(|voc| voc.metadata.identifier == vocabulary_id)
.collect::<Vec<Vocabulary>>();
Run Code Online (Sandbox Code Playgroud)
这不起作用.我得到的错误是:
the trait `std::iter::FromIterator<&app_structs::Vocabulary>` is not implemented for `std::vec::Vec<app_structs::Vocabulary>` [E0277]
Run Code Online (Sandbox Code Playgroud)
我不知道如何实施任何FromIterator,也不知道为什么这是必要的.在同一个Web应用程序中的另一个路径中,我执行以下相同的文件,其工作原理:
let result: Vec<String> = vocabulary_context.vocabularies.iter()
.filter(|voc| voc.metadata.identifier.as_str().contains(vocabulary_id))
.map(encode_to_string)
.collect::<Vec<String>>();
result.join("\n\n") // returning
Run Code Online (Sandbox Code Playgroud)
所以它似乎String实现了FromIterator.
但是,我没有得到,为什么我不能简单地Vec从the filter或collect方法中获取元素. …