如何使用泛型方法实现特征

如何使用泛型方法实现特征

本文介绍了如何使用泛型方法实现特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个包含通用方法的特征.

I'm trying to implement a trait which contains a generic method.

trait Trait {
    fn method<T>(&self) -> T;
}

struct Struct;

impl Trait for Struct {
    fn method(&self) -> u8 {
        return 16u8;
    }
}

我明白了:

error[E0049]: method `method` has 0 type parameters but its trait declaration has 1 type parameter
 --> src/lib.rs:8:5
  |
2 |     fn method<T>(&self) -> T;
  |     ------------------------- expected 1 type parameter
...
8 |     fn method(&self) -> u8 {
  |     ^^^^^^^^^^^^^^^^^^^^^^ found 0 type parameters

我应该如何正确编写 impl 块?

How should I write the impl block correctly?

推荐答案

函数和方法中的类型参数通用.这意味着对于所有 trait 实现者,Trait::method 必须为任何 T 实现,其约束与 trait 所指示的约束完全相同(在这种情况下,T 上的约束只是隐含的 Sized).

Type parameters in functions and methods are universal. This means that for all trait implementers, Trait::method<T> must be implemented for any T with the exact same constraints as those indicated by the trait (in this case, the constraint on T is only the implicit Sized).

您指出的编译器错误消息表明它仍然需要参数类型 T.相反,您的 Struct 实现假设 T = u8,这是不正确的.类型参数由方法的调用者而不是实现者决定,因此 T 可能并不总是 u8.

The compiler's error message that you indicated suggests that it was still expecting the parameter type T. Instead, your Struct implementation is assuming that T = u8, which is incorrect. The type parameter is decided by the caller of the method rather than the implementer, so T might not always be u8.

如果您希望让实现者选择特定类型,则必须改为在关联类型中具体化.

If you wish to let the implementer choose a specific type, that has to be materialized in an associated type instead.

trait Trait {
    type Output;

    fn method(&self) -> Self::Output;
}

struct Struct;

impl Trait for Struct {
    type Output = u8;

    fn method(&self) -> u8 {
        16
    }
}

另请阅读Rust 编程语言的这一部分:在具有关联类型的特征定义中指定占位符类型.

Read also this section of The Rust Programming Language: Specifying placeholder types in trait definitions with associated types.

另见:

这篇关于如何使用泛型方法实现特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:55