Boxed dyn Iterator Source Dispatch

Choosing between numeric sources at runtime returns Box<dyn Iterator>, giving callers one concrete type instead of threading generic parameters through.

RustData Fetching

Code

rustsnippet
18 lines
use std::iter;

// 两种来源在运行时二选一:装箱成 Box<dyn Iterator> 后
// 调用方拿到同一个类型,不需要把泛型参数层层传递
fn source(kind: &str) -> Box<dyn Iterator<Item = u32>> {
    match kind {
        "seq" => Box::new(1..=5),
        "powers" => Box::new(iter::successors(Some(2u32), |v| v.checked_mul(2)).take(4)),
        _ => Box::new(iter::repeat(0).take(3)),
    }
}

fn main() {
    for kind in ["seq", "powers", "unknown"] {
        let values: Vec<u32> = source(kind).collect();
        println!("{kind}: {values:?}");
    }
}

How the snippet works

One way to read it: the functions source and main, doing all the work.

The file repeats itself only inside for kind in ["seq", "powers", "unknown"]. A match spells out every case; omit one and the code does not compile.

What to watch for

  • No dependencies section needed; the standard library is the whole story.

Applying it

Entry signature: fn source(kind: &str) -> Box<dyn Iterator<Item = u32>>

The sequence source lives in main; running the file triggers it.

Statements that matter most here

fn source(kind: &str) -> Box<dyn Iterator<Item = u32>> {
    match kind {
        "seq" => Box::new(1..=5),
        "powers" => Box::new(iter::successors(Some(2u32), |v| v.checked_mul(2)).take(4)),
        _ => Box::new(iter::repeat(0).take(3)),
    }
}
let values: Vec<u32> = source(kind).collect();

Interactive Tools for This Topic

FAQ

How do you run Boxed dyn Iterator Source Dispatch?
Execute it straight away — the program needs nothing beyond the runtime.