gpt4 book ai didi

iterator - 为什么 Iterator::all 需要迭代器是可变的?

转载 作者:行者123 更新时间:2023-11-29 08:02:05 27 4
gpt4 key购买 nike

我在 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 方法不应该改变迭代器。像 mapfilter,它们将 self 而不是 mut self 作为参数。

我的 reference for map / filter / all .

我看到了an issue on the matter , 但没有给出任何解释。

最佳答案

迭代任何东西需要改变迭代器,因为Iterator::next采用&mut self。检查迭代器中的所有值需要迭代,因此 Iterator::all(以及许多类似的方法)也需要 &mut self

The all method should not have to alter the the iterator.

我很想听听您建议如何在调用next 的情况下检查迭代器中的每个值。

Like map or filter

这些方法返回一个新的迭代器,它们不调用next。话虽如此,如果他们愿意,他们可以这样做,因为......

which take self and not mut self as an argument.

可变性是变量所有者的属性。这两个函数是等价的:

fn example(mut a: String) {}
fn example(a: String) {
let mut a = a;
}

重要的是,两者在生成的文档中看起来是一样的——签名中都没有 mut。这是因为这对调用者来说无关紧要。

关于iterator - 为什么 Iterator::all 需要迭代器是可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993119/

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