我正在使用一个迭代器来遍历一个字符串的字符:
这会引发编译错误:
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
作为参数。
我看到了有关此问题的问题,但没有解释。