是否可以为由所有实现特征的类型组成的任何元组自动实现特征? [英] Is it possible to automatically implement a trait for any tuple that is made up of types that all implement the trait?

查看:67
本文介绍了是否可以为由所有实现特征的类型组成的任何元组自动实现特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个

trait Happy {}

我可以为我想要的任何结构实现 Happy,例如:

I can implement Happy for whatever struct I might want, for example:

struct Dog;
struct Cat;
struct Alligator;

impl Happy for Dog {}
impl Happy for Cat {}
impl Happy for Alligator {}

现在,我想自动 impl 我的 Happy trait 来处理任何由实现 Happy trait 的类型组成的元组.直觉上,所有快乐的元组也是快乐的.

Now, I would like to automatically impl my Happy trait for whatever tuple is made up of types that all implement the Happy trait. Intuitively, a tuple of all happy is happy as well.

有没有可能做这样的事情?例如,我可以轻松地将 Happy 的实现扩展到两个 Happy 类型的任何元组:

Is it possible to do such a thing? For example, I can trivially extend the implementation of Happy to whatever tuple of two Happy types:

impl <T, Q> Happy for (T, Q) where T: Happy, Q: Happy {}

因此,这可以完美编译:

As a result, this compiles perfectly:

fn f(_: impl Happy) {
}

fn main() {
    f((Dog{}, Alligator{}));
}

但是我如何将其推广到任何长度的元组?就我的理解而言,我们在 Rust 中没有可变泛型.有解决方法吗?

But how could I generalize that to any tuple, of any length? As far as my understanding goes, we don't have variadic generics in Rust. Is there a workaround?

推荐答案

我们在 Rust 中没有可变泛型.

we don't have variadic generics in Rust.

正确.

有解决方法吗?

您使用宏:

trait Happy {}

macro_rules! tuple_impls {
    ( $head:ident, $( $tail:ident, )* ) => {
        impl<$head, $( $tail ),*> Happy for ($head, $( $tail ),*)
        where
            $head: Happy,
            $( $tail: Happy ),*
        {
            // interesting delegation here, as needed
        }

        tuple_impls!($( $tail, )*);
    };

    () => {};
}

tuple_impls!(A, B, C, D, E, F, G, H, I, J,);

现在编译:

fn example<T: Happy>() {}

fn call<A: Happy, B: Happy>() {
    example::<(A, B)>();
} 

这通常不被视为大问题,因为长元组基本上是不可读的,如果确实需要,您总是可以嵌套元组.

This isn't generally seen as a big problem because long tuples are basically unreadable and you can always nest tuples if really needed.

另见:

这篇关于是否可以为由所有实现特征的类型组成的任何元组自动实现特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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