rust-lang/rust

impl Trait feature is not make code easy

3442853561 opened this issue · 3 comments

#![feature(conservative_impl_trait, universal_impl_trait)]

use std::ops::Sub;

trait Trait: Sub + Copy {}

impl Trait for i32{}

fn test0(foo: impl Trait) -> <impl Trait as std::ops::Sub>::Output {
    foo - foo
}

fn test1<T: Sub + Copy>(foo: T) -> T::Output {
    foo - foo
}

fn main() {
    let foo = test0(1);
    let bar = test1(1);
    println!("{:?}", bar);
}

Only the bar can be debug.

ExpHP commented
fn test0(foo: impl Trait) -> <impl Trait as std::ops::Sub>::Output {
    foo - foo
}

Should this even compile? I would have figured that the impl Trait in the output type should be considered ambiguous.

ExpHP commented

#48084 makes the snippet no longer compile.

   Compiling playground v0.0.1 (file:///playground)
error[E0667]: `impl Trait` is not allowed in path parameters
 --> src/main.rs:9:31
  |
9 | fn test0(foo: impl Trait) -> <impl Trait as std::ops::Sub>::Output {
  |                               ^^^^^^^^^^

That said, I can see what originally led the author to write this signature; observe the error message for an incorrect return type:

   Compiling playground v0.0.1 (file:///playground)
error[E0308]: mismatched types
  --> src/main.rs:10:5
   |
9  | fn test0(foo: impl Trait)  {
   |                            - possibly return type missing here?
10 |     foo - foo
   |     ^^^^^^^^^ expected (), found associated type
   |
   = note: expected type `()`
              found type `<impl Trait as std::ops::Sub>::Output`

Triage: the error message for foo0 is now

error[E0308]: mismatched types
  --> src/main.rs:10:5
   |
9  | fn test0(foo: impl Trait) {
   |                           - possibly return type missing here?
10 |     foo - foo
   |     ^^^^^^^^^ expected `()`, found associated type
   |
   = note:    expected unit type `()`
           found associated type `<impl Trait as Sub>::Output`
   = help: consider constraining the associated type `<impl Trait as Sub>::Output` to `()`
   = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html

Maybe that's helpful enough? This definitely doesn't seem like a bug though, I'm going to change it to a diagnostic request.