相关疑难解决方法(0)

如何在Rust中过滤自定义结构的向量?

我试图筛选Vec<Vocabulary>这里Vocabulary是一个自定义的struct,它本身包含一个struct VocabularyMetadataVec<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>.

这里是我当前的代码试图filterVec<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 filtercollect方法中获取元素. …

struct filtering vector rust

10
推荐指数
1
解决办法
9047
查看次数

标签 统计

filtering ×1

rust ×1

struct ×1

vector ×1