带有迭代器的 Rust 函数和 returns 带有变异项的迭代器?

Rust function that takes an iterator, and returns an iterator with mutated items?

我想编写一个函数,将一个迭代器作为输入,return 一个具有相同项但发生了变化的迭代器。就像这个例子:

fn greet(name: &mut String) {
    name.insert_str(0, "Hello ");
}

fn to_greetings(names: impl Iterator<Item = String>) -> impl Iterator<Item = String> {
    names.inspect(|name| greet(name))
}

这不会编译,因为 name 不可变。我曾尝试在不同的地方添加 mut 但没有真正理解我在做什么,但没有成功。我该如何修复上面的代码?

我想我需要让项目可变,但显然 Item = mut String 是一个语法错误。

如果迭代器的项类型是 String,则迭代器生成 owned 个字符串。迭代器将这些字符串的所有权转移给消费者。消费者可以修改字符串,因为它拥有它们。

但是,您不能使用 inspect() 修改迭代器的元素。传递给 inspect() 的闭包接收到迭代器项的不可变引用,不能用于修改项。修改项目的正确迭代器适配器是 map(),所以这有效(但对我来说并不特别惯用):

fn to_greetings<I>(names: I) -> impl Iterator<Item = String>
where
    I: Iterator<Item = String>,
{
    names.map(|mut name| { greet(&mut name); name })
}

如果你想实际修改一些底层容器中的字符串,例如一个字符串向量,但你需要一种不同的方法。字符串容器上的可变迭代器的项类型为 &mut String,因此您需要使用类似

的内容
fn to_greetings<'a, I>(names: I) -> impl Iterator<Item = &'a mut String>
where
    I: Iterator<Item = &'a mut String>,
{
    names.map(|name| { greet(name); name })
}