gpt4 book ai didi

rust - 为什么要借这个?

转载 作者:行者123 更新时间:2023-12-05 01:53:05 24 4
gpt4 key购买 nike

摘自本书,listing 13-29 :

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}

在对上述内容进行解释后,请读者“也可以随意在 search_case_insensitive 函数中使用迭代器方法进行相同的更改。”不要介意我这样做:

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.to_lowercase().contains(query.to_lowercase()))
.collect()
}

没有:

error[E0277]: expected a `FnMut<(char,)>` closure, found `String`
--> src/lib.rs:59:53
|
59 | .filter(|line| line.to_lowercase().contains(query.to_lowercase()))
| -------- ^^^^^^^^^^^^^^^^^^^^ expected an implementor of trait `Pattern<'_>`
| |
| required by a bound introduced by this call
|
= note: the trait bound `String: Pattern<'_>` is not satisfied
= note: required because of the requirements on the impl of `Pattern<'_>` for `String`
note: required by a bound in `core::str::<impl str>::contains`
help: consider borrowing here
|
59 | .filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
| +

确实,这会编译并通过前面示例中的测试:

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
.collect()
}

就此而言,如果借用querysearch 将编译并通过:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.contains(&query))
.collect()
}

那么为什么必须在 search_case_insensitive 中借用 query 但它是否是引用对 search 没有影响?

最佳答案

方法str::contains()将泛型 P: ​​Pattern 作为谓词。 The Pattern traitchar&char&String&[char]&str 实现, &&str, [字符; N], &[字符; N]F,其中 F:FnMut(char) -> bool。所有这些都可以传递给 contains()。但是,它没有为 String 实现。所以在 search() 中,您传递了 &str。没关系。借用的话,传&&str,也行。但是在 search_case_insensitive() 中,如果你借用你传递 &String 就没问题,但如果你不借用,你传递 String 就不行实现 Pattern 特性。

关于rust - 为什么要借这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71245144/

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