是否可以为由所有实现该特征的类型组成的任何元组自动实现特征? [英] Is it possible to automatically implement a trait for any tuple that is made up of types that all implement the trait?
问题描述
假设我有一个
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
特征,用于由所有实现 Happy
特征的类型组成的任何元组.直观地说,所有快乐的元组也是快乐的.
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 {}
结果,编译完美:
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屋!