Rust

impl Trait — Static Dispatch Returns

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you want to return a complex iterator chain or closure, you don't need to spell out the type. `impl Trait` lets the compiler infer the concrete type while exposing only the API contract.
Rust
Raw
// Returns "some iterator yielding i32" — concrete type stays hidden.
fn evens_up_to(n: i32) -> impl Iterator<Item = i32> {
    (0..n).filter(|x| x % 2 == 0)
}

// Closures have anonymous types — impl Fn is the way to return one.
fn adder(x: i32) -> impl Fn(i32) -> i32 {
    move |y| x + y
}

fn main() {
    for n in evens_up_to(10) {
        print!("{n} ");        // 0 2 4 6 8
    }
    println!();

    let add5 = adder(5);
    println!("{}", add5(3));    // 8
    println!("{}", add5(10));   // 15
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.