ジェネリクス関数 - impl trait引数とトレイト境界の違い

元ネタ

rust - What are the differences between an impl trait argument and generic function parameter? - Stack Overflow

回答

impl trait引数は、トレイト境界に脱糖(desugar)される。(ゆえにトレイト境界の糖衣構文である)

したがって以下は同じ。

trait Foo {}

fn func1(_: impl Foo) {}

fn func2<T: Foo>(_: T) {}

唯一の違いは、impl Trait引数は、その型を明白に指定させることができない。(ターボフィッシュが使えない)

trait Trait {}

fn foo<T: Trait>(t: T) {}
fn bar(t: impl Trait) {}

impl Trait for u32 {}

fn main() {
    foo::<u32>(0); // this is allowed
    bar::<u32>(0); // this is not
    /*
     error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
  --> src/main.rs:10:11
   |
10 |     bar::<u32>(0); // this is not
   |           ^^^ explicit generic argument not allowed
    */
}