首页 > 解决方案 > str::contains 适用于引用但不适用于实际值

问题描述

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

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参考的地方。有人可以解释一下吗?

标签: stringrust

解决方案


因为Pattern是为&'a String但不是为String

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

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

Jmb回复了

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


推荐阅读