预期的类型参数,找到u8,但类型参数是u8

Hos*_*our 5 types type-inference compiler-errors rust

trait Foo {
    fn foo<T>(&self) -> T;
}

struct Bar {
    b: u8,
}

impl Foo for Bar {
    fn foo<u8>(&self) -> u8 {
        self.b
    }
}

fn main() {
    let bar = Bar {
        b: 2,
    };
    println!("{:?}", bar.foo());
}
Run Code Online (Sandbox Code Playgroud)

(游乐场)

上面的代码导致以下错误:

error[E0308]: mismatched types
  --> <anon>:11:9
   |
11 |         self.b
   |         ^^^^^^ expected type parameter, found u8
   |
   = note: expected type `u8` (type parameter)
              found type `u8` (u8)
Run Code Online (Sandbox Code Playgroud)

我的猜测是,问题来自特质中的泛型函数.

oli*_*obk 9

以下代码不符合您的预期

impl Foo for Bar {
    fn foo<u8>(&self) -> u8 {
        self.b
    }
}
Run Code Online (Sandbox Code Playgroud)

它引入了一种称为u8阴影混凝土类型的泛型类型u8.你的功能将与100%相同

impl Foo for Bar {
    fn foo<T>(&self) -> T {
        self.b
    }
}
Run Code Online (Sandbox Code Playgroud)

可在这种情况下不能工作,因为T,被选择的呼叫者foo,则不能保证u8.

要解决此问题,请选择不与具体类型名称冲突的泛型类型名称.请记住,在执行函数签名具有相匹配的特征定义签名.


要解决所提出的问题,您希望将泛型类型修复为特定值,可以将泛型参数移动到特征,并为以下内容实现特征u8:

trait Foo<T> {
    fn foo(&self) -> T;
}

struct Bar {
    b: u8,
}

impl Foo<u8> for Bar {
    fn foo(&self) -> u8 {
        self.b
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用相关的特性,如果你从不想要Foo特定类型的多个impl(感谢@MatthieuM):

trait Foo {
    type T;
    fn foo(&self) -> T;
}

struct Bar {
    b: u8,
}

impl Foo for Bar {
    type T = u8;
    fn foo(&self) -> u8 {
        self.b
    }
}
Run Code Online (Sandbox Code Playgroud)