我试图过滤一个包含自定义结构体
Vocabulary
的Vec<Vocabulary>
,其中Vocabulary
包含一个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
的元素。
我如何过滤我的Vec
并简单地获取满足条件的Vec<Vocabulary>
元素?
&
。完全忽略了它。我不明白使用对Vocabulary
的引用并只给我引用处的对象有什么问题。是关于对象(结构体,包含另一个Vec等)大小未知的问题吗?对我来说,只有(1)第一种解决方案可行,因为(2)std::clone::Clone
也无法满足,而(3)仍然是不匹配的类型:app_structs::Vocabulary
与&app_structs::Vocabulary
。我会再次阅读into_iter
。我读到它是具有破坏性的,实际上想要所包含元素的副本,因此克隆可能是有意义的。 - Zelphir Kaltstahl&Vocabulary
引用的迭代器中获取Vec<Vocabulary>
。filter
只是一个trait的普通方法。编译器所知道的仅仅是它的签名fn collect<B>(self) -> B where B: FromIterator<Self::Item>
,因此它检查类型Vec<Vocabulary>
是否实现了traitFromIterator<&Vocabulary>
,发现它没有,并报告错误。 - red75prime|voc|
是什么意思吗?我来自 JS,从未见过这样的东西。 - bill.gates