Rust generic type parameter and `impl Trait` parameter

Rust generic type parameter and impl Trait parameter

(Jin Qing’s Column, Jun., 2023)

See: https://doc.rust-lang.org/reference/types/impl-trait.html

Generic type parameter and impl Trait parameter are almost equivalent:

trait Trait {}

// generic type parameter
fn foo<T: Trait>(arg: T) {
}

// impl Trait parameter
fn foo(arg: impl Trait) {
}

impl Trait is just a syntactic sugar for generic type parameter.
It is a little simpler by omitting the generic parameters <...>.

But they are not exactly equivalent.

The caller can use a generic argument to specify the type of the generic parameter T,
for example, foo::<usize>(1), but not for the impl Trait parameter.

Therefore, changing the function signature from either one to the other
can constitute a breaking change.

猜你喜欢

转载自blog.csdn.net/jq0123/article/details/131314484