【问题标题】:Is it possible to automatically implement a trait for any tuple that is made up of types that all implement the trait?是否可以为由所有实现该特征的类型组成的任何元组自动实现特征?
【发布时间】:2019-04-06 20:38:30
【问题描述】:

假设我有一个

trait Happy {}

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

struct Dog;
struct Cat;
struct Alligator;

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

现在,对于由所有实现 Happy 特征的类型组成的任何元组,我想自动 impl 我的 Happy 特征。直观地说,所有快乐的元组也是快乐的。

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

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

结果,编译完美:

fn f(_: impl Happy) {
}

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

但是我怎么能把它推广到任何长度的任何元组呢?据我了解,Rust 中没有可变参数泛型。有解决办法吗?

【问题讨论】:

标签: rust tuples traits variadic


【解决方案1】:

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

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

另见:

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多