一次为多种类型实现一个特征 [英] Implementing a trait for multiple types at once

查看:29
本文介绍了一次为多种类型实现一个特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个结构体和一个特征:

I have two structs and a trait:

struct A {
    x: u32,
}

struct B {
    x: u32,
}

trait T {
    fn double(&self) -> u32;
}

我想使用 x 为两个结构实现 T.

I would like to implement T for both structs using x.

有没有办法写类似的东西

Is there a way to write something like

impl T for A, B {
    fn double(&self) -> u32 {
        /* ... */
    }
}

如果可能,我不想使用宏.

I would like to not use macros if possible.

推荐答案

为许多具体类型实现一个 trait 的唯一方法是为所有已经实现另一个 trait 的类型实现一个 trait.

The only way to implement a trait once for many concrete types is to implement a trait for all types already implementing another trait.

例如,您可以实现标记特征 Xed 然后:

For example, you can implement a marker trait Xed and then:

impl<T> Double for T
where
    T: Xed,
{
    fn double(&self) {
        /* ... */
    }
}

然而,Rust 有原则的泛型.你在前面的实现中唯一知道的关于 T 的是 T 实现了 Xed trait,因此您可以使用的唯一关联类型/函数是来自 Xed 的那些.

However, Rust has principled generics. The only thing that you know about T in the previous implementation is that T implements the Xed trait, and therefore the only associated types/functions you can use are those coming from Xed.

trait 不能暴露字段/属性,只能暴露相关的类型、常量和函数,所以 Xed 需要一个用于 x 的 getter(不需要被称为 x).

A trait cannot expose a field/attribute, only associated types, constants and functions, so Xed would need a getter for x (which need not be called x).

如果您希望依赖代码的句法(而不是语义)属性,请使用宏.

If you wish to rely on syntactic (and not semantic) properties of the code, then use macros.

这篇关于一次为多种类型实现一个特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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