但是类型参数是u8

但是类型参数是u8

本文介绍了预期的类型参数,找到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)

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

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 。您的函数将与

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.

通常要解决此问题,请选择与具体类型不冲突的通用类型名称类型名称。请记住,实现中的函数签名必须与trait定义中的签名匹配。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:55