Impl Trait vs trait bound syntax

Would the binary that Rust generates for the snipit of code 1 be larger than that of 2? I'm assuming that 1 would need to generate binary for every data-type for which there is an implementation for "Trait", and that 2 would not. I'm not sure.

fn function(x: impl Trait) {. . . x.method. . .}

fn function <T: Trait> (x: T) {. . . x.method. . .}

1 Like

I’d be extremely surprised if the compiled versions of those two functions weren’t identical.

3 Likes

They're the same under the hood in current Rust. But you (and consumers of the function) can't name the generic with impl Trait.

4 Likes

What makes you think that? Maybe you are confusing generics with dyn Trait?

In the argument position impl Trait is the same as regular generics, with the only difference that it doesn't allow the turbofish syntax.

impl Trait in the return position is very different.

3 Likes

I'm new.
I was reading a book where they seemed to imply that using something like <T: Some_Trait> limited the use of the function to particular data-types, whereas <x: impl Some_Trait> allowed for the use of any data-type for which there was an implementation. I assumed that the compiler would thus create binary for all of the data-types under the former and that one could limit the size of the binary somehow by limiting the data-types for which the function would be used.
dunno. It's easier to remember things if I understand the abstraction as opposed to just memorizing stuff.

That is not the case. The T: Trait trait bound syntax also allows any type that implements the trait. (In fact, argument-position impl Trait is not necessary, and I consider it a misfeature, as it is completely redundant with the – by the way older – T: Trait bounds.)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.