One example that `impl trait` and generic type parameters (trait bounds) are not exactly equivalent, but why?

I know the depiction of differences between generics and impl Trait in return position, but still don't get it here.

fn main() {
    a(0..10).map(|d| dbg!(d)).last();
}

// pass
fn a<T: Iterator<Item = u8>>(t: T) -> impl Iterator<Item = u8> {
    t.map(|x| x + 1)
}

// failed: mismatched types
fn b<T: Iterator<Item = u8>, U: Iterator<Item = u8>>(t: T) -> U {
    t.map(|x| x + 1)
}

// failed: mismatched types
fn c<T, U>(t: T) -> U
where
    T: Iterator<Item = u8>,
    U: Iterator<Item = u8>,
{
    t.map(|x| x + 1)
}
error[E0308]: mismatched types
  --> src/main.rs:12:5
   |
11 | fn b<T: Iterator<Item = u8>, U: Iterator<Item = u8>>(t: T) -> U {
   |                              - this type parameter            - expected `U` because of return type
12 |     t.map(|x| x + 1)
   |     ^^^^^^^^^^^^^^^^ expected type parameter `U`, found struct `Map`
   |
   = note: expected type parameter `U`
                      found struct `Map<T, [closure@src/main.rs:12:11: 12:20]>`

error[E0308]: mismatched types
  --> src/main.rs:21:5
   |
16 | fn c<T, U>(t: T) -> U
   |         -           - expected `U` because of return type
   |         |
   |         this type parameter
...
21 |     t.map(|x| x + 1)
   |     ^^^^^^^^^^^^^^^^ expected type parameter `U`, found struct `Map`
   |
   = note: expected type parameter `U`
                      found struct `Map<T, [closure@src/main.rs:21:11: 21:20]>`

For more information about this error, try `rustc --explain E0308`.

playground

Well, for example, what if I called b::<std::vec::IntoIter<u8>, std::vec::IntoIter<u8>>. Then you would be returning the wrong type.

1 Like

I.e., a generic type argument is chosen by the caller of the function, while impl Trait in return position is fixed by the function itself and cannot be changed.

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