【发布时间】:2017-11-23 13:03:19
【问题描述】:
我正在尝试过滤一个Vec<Vocabulary>,其中Vocabulary 是一个自定义struct,它本身包含一个struct VocabularyMetadata 和一个Vec<Word>:
#[derive(Serialize, Deserialize)]
pub struct Vocabulary {
pub metadata: VocabularyMetadata,
pub words: Vec<Word>
}
这用于处理 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>>();
这不起作用。我得到的错误是:
the trait `std::iter::FromIterator<&app_structs::Vocabulary>` is not implemented for `std::vec::Vec<app_structs::Vocabulary>` [E0277]
我不知道如何实现任何FromIterator,也不知道为什么需要这样做。在同一个网络应用程序的另一条路线中,我执行以下相同的文件,这很有效:
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
所以看来String 实现了FromIterator。
但是,我不明白,为什么我不能简单地从 filter 或 collect 方法中取回 Vec 的元素。
我如何filter 我的Vec 并简单地获取条件为真的Vec<Vocabulary> 的元素?
【问题讨论】:
标签: vector struct rust filtering