gpt4 book ai didi

string - str::contains 适用于引用但不适用于实际值

转载 作者:行者123 更新时间:2023-11-29 08:26:37 24 4
gpt4 key购买 nike

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

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 来引用。谁能解释一下?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com