预期类型参数,找到 u8,但类型参数是 u8 [英] Expected type parameter, found u8, but the type parameter is u8

查看:26
本文介绍了预期类型参数,找到 u8,但类型参数是 u8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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());
}

(游乐场)

以上代码导致以下错误:

The above code results in the following error:

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)

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

My guess is, the problem comes from generic function in trait.

推荐答案

下面的代码不符合你的预期

The following code does not do what you expect

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

它引入了一个名为 u8 的泛型类型,它隐藏了具体类型 u8.您的功能将 100% 与

It introduces a generic type called u8 which shadows the concrete type u8. Your function would be 100% the same as

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

在这种情况下不能工作,因为foo调用者选择的T不能保证是u8.

Which cannot work in this case because T, chosen by the caller of foo, isn't guaranteed to be u8.

一般要解决这个问题,选择与具体类型名称不冲突的泛型类型名称.请记住,实现中的函数签名必须与特征定义中的签名相匹配.

To solve this problem in general, choose generic type names that do not conflict with concrete type names. Remember that the function signature in the implementation has to match the signature in the trait definition.

要解决所提出的问题,您希望将泛型类型修复作为特定值,您可以将泛型参数移动到特征,并仅为 u8<实现特征/代码>:

To solve the issue presented, where you wish to fix the generic type as a specific value, you can move the generic parameter to the trait, and implement the trait just for u8:

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

struct Bar {
    b: u8,
}

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

或者你可以使用关联的特征,如果你不想为特定类型使用多个 Foo 实现(感谢@MatthieuM):

Or you can use an associated trait, if you never want multiple Foo impls for a specific type (thanks @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
    }
}

这篇关于预期类型参数,找到 u8,但类型参数是 u8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆