首先,请注意,我已经看到了How to filter a vector of custom structs?个,然而,它没有包含我问题的解决方案(或者至少我看不到一个).主要区别在于,在我的过滤器中,我try 使用字符串的CONTAIN()方法.如果我举个例子就更好了.
以下是我的 struct :
#[derive(Clone)]
pub struct Spell {
pub title: String,
pub code: String,
pub category: String,
pub sub_category: String,
pub tool: String,
pub file_name: String,
}
#[derive(Debug)]
pub struct SearchParameters {
pub category: String,
pub sub_category: String,
pub tool: String,
pub search_str: String,
}
下面是我try 在其中处理向量的函数:
pub fn search_spell(&self, search_parameters: SearchParameters) -> Vec<Spell> {
let tmp_results: Vec<Spell> = self
._spell_list
.clone()
.into_iter()
.filter(|spell| {
if search_parameters.category.is_empty() {
true
} else {
*spell.category == search_parameters.category
}
})
.filter(|spell| {
if search_parameters.sub_category.is_empty() {
true
} else {
*spell.sub_category == search_parameters.sub_category
}
})
.filter(|spell| {
if search_parameters.tool.is_empty() {
true
} else {
*spell.tool == search_parameters.tool
}
})
.filter(|spell| {
if search_parameters.search_str.is_empty() {
true
} else {
//*spell.title.contains(search_parameters.search_str)
true
}
})
.collect();
// TODO: replace this part by including in the filer above
let mut results: Vec<Spell> = Vec::new();
for spell in tmp_results {
if search_parameters.search_str.is_empty() {
results.push(spell);
} else {
if spell
.title
.to_lowercase()
.contains(&search_parameters.search_str.to_lowercase())
{
results.push(spell);
}
}
}
results
}
问题出在最后一个过滤器块(参见注释代码),其中我想使用.contains()
方法,而不是==
个比较.问题是,在编译时,编译器不能确定这个值到底是什么.
目前,我已经通过在此方法的末尾处理循环中的向量来解决这个问题,但如果您明白我的意思,这感觉有点勉强.我真的认为我应该能够在过滤器中以某种方式解决这个问题.