First of all, note that I have seen How to filter a vector of custom structs? already, however, it doesn't contain the solution to my issue (or at least I can't see one). The main difference is that in my filter I try to use contain() method of a string. It is better if I show it with an example.
Here are my structs:
#[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,
}
And here's the function I try to process the vector in:
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
}
The issue is with the last filter block (see the commented code), where instead of ==
comparison, I would like to use .contains()
method. The issue is that at the compile time, the compiler can't be sure what this value actually is.
For now, I have resolved this by processing the vector in the loop at the end of this method, but it feels a little bit forced if you know what I mean. I really think I should be able to resolve this somehow in the filter.