Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Confusing compiler error in generic implementations. #56183

Closed
popzxc opened this issue Nov 23, 2018 · 1 comment
Closed

Confusing compiler error in generic implementations. #56183

popzxc opened this issue Nov 23, 2018 · 1 comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints

Comments

@popzxc
Copy link
Contributor

popzxc commented Nov 23, 2018

This code (playground) produces a confusing error message:

pub struct MyType<T> {
    val: T,
}

impl<T: ToString> MyType<T> {
    pub fn new(val: T) -> Self {
        Self {
            val
        }
    }
    
    pub fn new_from_self(&self, val: u8) -> MyType<u8> {
        MyType {
            val
        }
    }

    pub fn new_from_self_generic(&self, val: u8) -> Self {
        Self {
            val
        }
    }
}

Method new_from_self compiles and works as expected, but new_from_self_generic produces an error: mismatched types, expected type T, found type u8.
As I understand this, such an error happens because type of T for self will be already deduced at the time of call, and it may be not u8, e.g.:

let my_type_string = MyType::new(String::new());
my_type_string.new_from_self_generic(2); // `T` is `String`, `Self` is `MyType<String>`, not `MyType<u8>`.

However, understanding of this fact took a while, and I had to write some additional code snippets just to understand what compiler wanted from me.
Thus I think that current error message is confusing and should be changed for similar cases at least to something more helpful.

@estebank estebank added the A-diagnostics Area: Messages for errors, warnings, and lints label Nov 24, 2018
@estebank
Copy link
Contributor

Current output after #63907:

error[E0308]: mismatched types
  --> src/lib.rs:20:13
   |
20 |             val
   |             ^^^ expected type parameter, found u8
   |
   = note: expected type `T`
              found type `u8`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

I'll close it given that and the existence of #63711, but if that output is not enough feel free to comment in #63711 and give your current input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints
Projects
None yet
Development

No branches or pull requests

2 participants