Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between an impl trait argument and generic function parameter?

Tags:

rust

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: Foo>(_: T) {}
like image 347
Boiethios Avatar asked Nov 27 '17 15:11

Boiethios


2 Answers

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<U>(self, f: impl FnOnce(T) -> U) -> Option<U>
fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U

However, one difference is that impl Trait arguments cannot have their types explicitly specified:

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

foo::<u32>(0) // this is allowed
bar::<u32>(0) // this is not

The 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.

like image 115
interjay Avatar answered Oct 18 '22 16:10

interjay


Both produce identical assembly, at least with the following simple test case:

trait Foo {}

struct Bar;

impl Foo for Bar {}

fn func1(_: impl Foo) {}

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

fn main() {
    let x = Bar;

    let y = func1(x); // or func2(x);
}
like image 23
ljedrz Avatar answered Oct 18 '22 17:10

ljedrz