← 中文资源

简体中文版本

into_iter 让元素经适配器链移动

into_iter 按值交出每个元素:map 里拿到的是所有权,适配器链一路移动 owned String;iter 只借用,源集合仍然可用,两种写法的所有权语义一目了然。

阅读英文原文

实现说明

into_iter 让元素经适配器链移动以函数 main为骨架。

使用要点

  • 每一步打印都带着自己的标签:upper:、lengths:、borrowed still there:。

常见问题

运行「into_iter 让元素经适配器链移动」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 upper:、lengths:、borrowed still there: 标签标明各步骤。

核心语句

let lengths: Vec<usize> = borrowed.iter().map(|name| name.len()).collect();
.chain(borrowed.iter().map(|s| s.to_string()))
.collect();
.map(|name| name.to_uppercase())
.collect();

代码示例

fn main() {
    let names = vec![String::from("deploy"), String::from("lint"), String::from("test")];

    // into_iter hands each element by value: adapters move owned Strings through
    let upper: Vec<String> = names
        .into_iter()
        .map(|name| name.to_uppercase())
        .collect();
    println!("upper: {upper:?}");

    // names was consumed by into_iter; this would not compile:
    // println!("{names:?}");

    let borrowed = vec!["deploy", "lint", "test"];
    // iter yields references instead, so the source stays usable
    let lengths: Vec<usize> = borrowed.iter().map(|name| name.len()).collect();
    println!("lengths: {lengths:?}");
    println!("borrowed still there: {borrowed:?}");

    // chain both styles: move one vec's elements, borrow another's
    let tags = vec![String::from("eu"), String::from("prod")];
    let mixed: Vec<String> = tags
        .into_iter()
        .chain(borrowed.iter().map(|s| s.to_string()))
        .collect();
    println!("mixed: {mixed:?}");
}