Iterator Flatten For Nested Sequences

Collapse nested iterators with flatten and expand one-to-many with flat_map, so empty inner collections and None values drop out without filtering loops.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    let batches: Vec<Vec<&str>> = vec![
        vec!["us-east-1", "us-east-2"],
        vec![], // 空内层被 flatten 自动跳过
        vec!["eu-west-1"],
    ];

    // flatten:去掉一层嵌套,空的内层自然消失
    let regions: Vec<&str> = batches.iter().flatten().copied().collect();
    println!("regions: {}", regions.join(", "));

    // flat_map = map + flatten:一个输入展开成多个输出
    let words = ["deploy plan", "now"];
    let initials: String = words.iter().flat_map(|w| w.chars().take(1)).collect();
    println!("initials: {initials}");

    // Option 是「0 或 1 个元素」的序列:flatten 统一跳过 None
    let readings = [Some(3), None, Some(5), Some(2)];
    let total: i32 = readings.into_iter().flatten().sum();
    println!("total: {total}");
}

How the snippet works

Count the function main as the entire surface area of Iterator Flatten For Nested Sequences.

Applying it

Running the file prints labeled results such as regions:, initials:, total: — each operation’s effect is visible in the output.

Statements that matter

let initials: String = words.iter().flat_map(|w| w.chars().take(1)).collect();
let regions: Vec<&str> = batches.iter().flatten().copied().collect();
let readings = [Some(3), None, Some(5), Some(2)];

Interactive Tools for This Topic

FAQ

What does Iterator Flatten For Nested Sequences print when run?
Execute the whole file; each printed line is prefixed with a label like `regions:`, `initials:`, `total:`.