← 中文资源

简体中文版本

用 into_keys 与 into_values 消费 map

into_keys 与 into_values 按所有权把 map 拆成键流和值流:键收集进有序集合、值直接求和或展平,全程零克隆。

阅读英文原文

实现说明

用 into_keys 与 into_values 消费 map的核心是函数 main。 重复被限制在 for route in ["GET /health", "POST /orders", "GET /health", "GET /users"] 里——其余代码按顺序各跑一遍。

使用要点

  • 直接运行文件,输出会带上标签,比如 routes (sorted):、total:、all tags:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「用 into_keys 与 into_values 消费 map」会打印什么?

运行文件本身,routes (sorted):、total:、all tags: 这些前缀各对应一段演示逻辑。

核心语句

let mut all: Vec<&str> = tags.into_values().flatten().collect();
let routes: BTreeSet<String> = counts.into_keys().collect();
let total: u64 = counts.into_values().sum();

代码示例

use std::collections::{BTreeSet, HashMap};

fn main() {
    // a request-count table: taken apart by ownership once processing finishes
    let mut counts: HashMap<String, u64> = HashMap::new();
    for route in ["GET /health", "POST /orders", "GET /health", "GET /users"] {
        *counts.entry(route.to_string()).or_insert(0) += 1;
    }

    // into_keys consumes the map: ownership of the keys moves wholesale, collected into a sorted set
    let routes: BTreeSet<String> = counts.into_keys().collect();
    println!("routes (sorted):");
    for route in &routes {
        println!("  {route}");
    }

    // rebuilding the map shows into_values: ownership of the values moves, summed directly
    let mut counts: HashMap<String, u64> = HashMap::new();
    counts.insert("a".to_string(), 3);
    counts.insert("b".to_string(), 5);
    let total: u64 = counts.into_values().sum();
    println!("total: {total}");

    // the same works when values are complex types: into_values hands over owned elements
    let mut tags: HashMap<&str, Vec<&str>> = HashMap::new();
    tags.insert("rust", vec!["systems", "compiled"]);
    tags.insert("go", vec!["concurrent"]);
    let mut all: Vec<&str> = tags.into_values().flatten().collect();
    all.sort_unstable(); // HashMap has no order: sorting before display keeps output stable
    println!("all tags: {all:?}");
}