Consider a function that searches for a pattern in a huge string of lines and returns the lines on which matches are found:
fn search_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
let lowercase_query = query.to_lowercase();
let mut matches: Vec<&str> = Vec::new();
for line in content.lines() {
let lowercase_line = line.to_lowercase();
if lowercase_line.contains(&lowercase_query) {
matches.push(line)
}
}
matches
}
The question I have is around the line if lowercase_line.contains(&lowercase_query)
. Why is lowercase_query
passed as a reference here? If I pass it as a value instead I get the error:
error[E0277]: expected a `std::ops::FnMut<(char,)>` closure, found `std::string::String`
--> src/lib.rs:6:27
|
6 | if lowercase_line.contains(lowercase_query) {
| ^^^^^^^^ expected an `FnMut<(char,)>` closure, found `std::string::String`
|
= help: the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
I checked the definition of the contains
function:
pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
pat.is_contained_in(self)
}
I don't see anywhere the need for contains
to take a reference. Can someone explain this?