string - 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
参考的地方。有人可以解释一下吗?
解决方案
因为Pattern
是为&'a String
但不是为String
impl<'a, 'b> Pattern<'a> for &'b String
但是当我按值传递错误消息时,我仍然没有得到它之间的关系
Jmb回复了
如果您查看 Pattern 的文档,您会看到最后记录的 impl 是针对FnMut (char) -> bool的,这可能解释了为什么编译器选择显示该特定类型。如果编译器说 impl Pattern<'_> 可能会更好
推荐阅读
- python - 使用 pycountry 从 iso-639 代码中获取完整的语言名称
- python - 在没有 PnP 的情况下在单目视觉里程计中查找相对比例
- flutter - 加载数据时更改 FutureBuilder 中的状态
- json - 在 Flutter 中对 Json 进行排序
- layout - 盖茨比的每一页都需要 GSAP 时间线
- xcode - mac os - “信任请求错误(-402,653,181)”
- azure - 适用于 Microsoft IIS httpd 10.0 的基于 Azure PCI 合规性 CPE 的漏洞
- python - 如何通过在python中迭代句子中的单词来创建表格?
- firebase - Django rest 不调用自定义身份验证后端?
- python - 如何使用 Yolo 对象检测在推理上平铺图像