str :: contains使用引用但不使用实际值

时间:2019-02-28 06:57:38

标签: string rust

考虑一个函数,该函数在巨大的字符串行中搜索模式并返回找到匹配项的行:

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需要参考。有人可以解释吗?

1 个答案:

答案 0 :(得分:2)

因为Pattern是为&'a String实现的,而不是String

impl<'a, 'b> Pattern<'a> for &'b String

  

但是当我按值传递错误消息时,我仍然没有得到错误消息之间的关系

得到Jmb

的答复
  

如果查看Pattern的文档,您会发现最后记录的impl是针对FnMut (char) -> bool的,这可能解释了为什么编译器选择显示该特定类型。如果编译器说了impl Pattern <'_>

,可能会更好。