rust

What does `impl` mean when used as the argument type or return type of a function?


I read this code:

pub fn up_to(limit: u64) -> impl Generator<Yield = u64, Return = u64> {
    move || {
        for x in 0..limit {
             yield x;
        }
        return limit;
    }
}

What does impl mean? How might this be implemented in plain Rust or C++?


Solution

  • This is the new impl Trait syntax which allows the programmer to avoid naming generic types. The feature is available as of Rust 1.26.

    Here, it is used in return position to say "the type returned will implement this trait, and that's all I'm telling you". In this case, note that all return paths of the function must return the exact same concrete type.

    The syntax can also be used in argument position, in which case the caller decides what concrete type to pass.

    See also: