Impl Trait Accepts One Anonymous Type

Argument-position impl Trait is an unnamed generic parameter: each call site picks one concrete type, and callers never see the hidden name.

RustData Integrity

Code

rustsnippet
23 lines
// 参数位置的 impl Trait:等价于匿名的泛型参数 T: Iterator<Item = i32>,
// 每个调用点由编译器确定一个具体类型,签名上不暴露类型名。
fn sum_positive(items: impl Iterator<Item = i32>) -> i32 {
    items.filter(|v| *v > 0).sum()
}

// 显式泛型写法完全等价,只是签名更长:
fn sum_positive_explicit<I: Iterator<Item = i32>>(items: I) -> i32 {
    items.filter(|v| *v > 0).sum()
}

fn main() {
    let xs = vec![-3, 5, -1, 8];
    // Vec 的借用迭代器满足约束:两种写法都能接受同一个调用点
    let a = sum_positive(xs.iter().copied());
    let b = sum_positive_explicit(xs.iter().copied());
    println!("impl trait: {a}, explicit generic: {b}");

    // 每个调用点可以换成不同来源:数组、Range 都行
    let c = sum_positive([-2, 7].into_iter());
    let d = sum_positive(1..=4);
    println!("array: {c}, range: {d}");
}

What this snippet does

The active parts are the functions sum_positive, sum_positive_explicit and main — everything else is wiring.

Points of care

  • Everything it calls is documented as part of the language core.

Applying it

The one signature to note: fn sum_positive(items: impl Iterator<Item = i32>) -> i32

Output lines are prefixed (impl trait:, array:), so each step’s outcome reads clearly.

Launch the file; main takes over and steps through sum_positive and sum_positive_explicit.

Statements that matter

fn sum_positive(items: impl Iterator<Item = i32>) -> i32 {
    items.filter(|v| *v > 0).sum()
}
fn sum_positive_explicit<I: Iterator<Item = i32>>(items: I) -> i32 {
    items.filter(|v| *v > 0).sum()
}
let b = sum_positive_explicit(xs.iter().copied());

Interactive Tools for This Topic

FAQ

What does Impl Trait Accepts One Anonymous Type print when run?
Execute the whole file; each printed line is prefixed with a label like `impl trait:`, `array:`.