Rust 中“.map(|&x| x)”的用途是什么

What's the purpose of ".map(|&x| x)" in Rust

我正在学习 Rust 并在很多地方注意到以下迭代器模式:

let some_vector: &[& str] = &["hello", "world", "zombies", "pants"];
let result: Vec<&str> = some_vector
    .iter()
    .filter(|&x| *x == "hello")
    .map(|&x| x)
    .collect();

那个.map(|&x| x)的目的是什么?为什么有必要?它会创建副本吗?

当我删除它时,出现以下编译器错误:

error[E0277]: a value of type `Vec<&str>` cannot be built from an iterator over elements of type `&&str`
    --> src/main.rs:7:6
     |
7    |     .collect();
     |      ^^^^^^^ value of type `Vec<&str>` cannot be built from `std::iter::Iterator<Item=&&str>`
     |
     = help: the trait `FromIterator<&&str>` is not implemented for `Vec<&str>`
note: required by a bound in `collect`

For more information about this error, try `rustc --explain E0277`.

所以 map 将字符串切片引用的迭代器转换为字符串切片的迭代器?删除一级间接?是吗?

假设您使用的是 2021 版,它会从 impl Iterator< Item = &&str> 转换为 impl Iterator< Item = &str>

let some_vector: &[& str] = &["hello", "world", "zombies", "pants"];
let result: Vec<&str> = some_vector // &[&str]
    .iter()                         // Iter<&str>
    .filter(|&x| *x == "hello")     // Impl Iterator< Item = &&str>
    .map(|&x| x)                    // Impl Iterator< Item = &str>
    .collect();

之所以有必要,是因为 FromIterator 特征已经为 &str 实现,因为它是一个相对更常见的用例,并且没有为 &&str 实现作为错误消息说:

the trait `FromIterator<&&str>` is not implemented for `Vec<&str>`

除了@AlexW的回答,其实没必要写那个,因为有一个内置的迭代器适配器做得更好(更清晰,更高效):copied().

let some_vector: &[&str] = &["hello", "world", "zombies", "pants"];
let result: Vec<&str> = some_vector
    .iter()
    .filter(|&x| *x == "hello")
    .copied()
    .collect();

还有cloned()等于.map(|x| x.clone()).