考虑一个函数,该函数在巨大的字符串行中搜索模式并返回找到匹配项的行:
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
}
我的问题是if lowercase_line.contains(&lowercase_query)
。为什么在这里通过lowercase_query
作为参考?如果我将其作为值传递,则会收到错误:
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`
我检查了contains
函数的定义:
pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
pat.is_contained_in(self)
}
我看不出有任何地方contains
需要参考。有人可以解释吗?
答案 0 :(得分:2)
因为Pattern
是为&'a String
实现的,而不是String
是
impl<'a, 'b> Pattern<'a> for &'b String
但是当我按值传递错误消息时,我仍然没有得到错误消息之间的关系
得到Jmb
的答复如果查看Pattern的文档,您会发现最后记录的impl是针对FnMut (char) -> bool的,这可能解释了为什么编译器选择显示该特定类型。如果编译器说了impl Pattern <'_>
,可能会更好。