patternrustModerate
What are the differences between an impl trait argument and generic function parameter?
Viewed 0 times
areargumentfunctionandbetweenparameterthedifferencesimplgeneric
Problem
impl Traits can be used as function arguments. Are there differences between this and a generic function with a trait constraint?trait Foo {}
fn func1(_: impl Foo) {}
fn func2(_: T) {}Solution
impl Traits as function arguments are desugared to an anonymous generic parameter. See the RFC, which says:Expand
impl Trait to allow use in arguments, where it behaves like an anonymous generic parameter.There's also an example in the RFC:
// These two are equivalent
fn map(self, f: impl FnOnce(T) -> U) -> Option
fn map(self, f: F) -> Option where F: FnOnce(T) -> UHowever, one difference is that
impl Trait arguments cannot have their types explicitly specified:fn foo(t: T)
fn bar(t: impl Trait)
foo::(0) // this is allowed
bar::(0) // this is notThe Motivation for expanding to argument position section explains why additional syntax was added for an existing feature. In short, it's for having similar syntax as
impl traits in function return position, which improves learnability, and to improve ergonomics.Code Snippets
// These two are equivalent
fn map<U>(self, f: impl FnOnce(T) -> U) -> Option<U>
fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> Ufn foo<T: Trait>(t: T)
fn bar(t: impl Trait)
foo::<u32>(0) // this is allowed
bar::<u32>(0) // this is notContext
Stack Overflow Q#47514930, score: 46
Revisions (0)
No revisions yet.