Skip to content

Confusing compiler error in generic implementations. #56183

Closed
@popzxc

Description

@popzxc

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions