我在String
的字符上使用了迭代器:
pub fn is_yelling(message: &str) -> bool {
let letters = message.chars().filter(|c| c.is_alphabetic());
message.chars().any(|c| c.is_alphabetic()) && letters.all(|c| c.is_uppercase())
}
这会引发编译错误:
error[E0596]: cannot borrow immutable local variable `letters` as mutable
--> src/main.rs:3:51
|
2 | let letters = message.chars().filter(|c| c.is_alphabetic());
| ------- consider changing this to `mut letters`
3 | message.chars().any(|c| c.is_alphabetic()) && letters.all(|c| c.is_uppercase())
| ^^^^^^^ cannot borrow mutably
当我变得letters
可变时,一切都会顺利进行。
我不明白为什么这样做是必要的。该all
方法不必更改迭代器。像map
或filter
,以self
和不mut self
作为参数。
迭代任何事情都需要更改迭代器,因为Iterator::next
Takes &mut self
。检查迭代器中的所有值都需要迭代,因此Iterator::all
(以及许多类似方法)也需要迭代&mut self
。
该
all
方法不必更改迭代器。
我非常有兴趣听到您建议如何在不调用的情况下检查迭代器中的每个值next
。
喜欢
map
或filter
这些方法返回一个新的迭代器,它们不会调用next
。话虽如此,他们可以,因为...
其采取
self
和不mut self
作为参数。
可变性是变量所有者的属性。这两个功能是等效的:
fn example(mut a: String) {}
fn example(a: String) {
let mut a = a;
}
重要的是,两者在生成的文档中看起来相同-mut
签名中都没有。这是因为它与调用方无关。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句