我试图过滤一个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>
.
下面是我当前try 在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
,也不知道为什么这是必要的.在同一个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
所以String
代表FromIterator
.
然而,我不明白,为什么我不能简单地从filter
或collect
方法中得到Vec
的元素.
我怎样才能在我的Vec
中输入filter
,然后简单地得到Vec<Vocabulary>
中的元素,条件为真?