假设我有一个
trait Happy {}
我可以为我想要的任何结构实现Happy
,例如:
struct Dog;
struct Cat;
struct Alligator;
impl Happy for Dog {}
impl Happy for Cat {}
impl Happy for Alligator {}
现在,我想自动impl
我的Happy
特性为任何元组由所有实现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中没有variadic泛型。有解决方法吗?
我们在Rust中没有variadic泛型。
正确。
有解决方法吗?
你使用宏:
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)>();
}
这通常不被视为一个大问题,因为长元组基本上是不可读的,如果真的需要你总是可以嵌套元组。
也可以看看: