Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Macros: How to make impl Trait for tuple better
Sometimes, we need to impl trait for tuple. The solution is macro_rules, for example:
macro_rules! impl_query {
($($i: literal),+ $(,)?) => {
paste! {
impl<$([<T $i>]),+, C> Query<C, ((),)> for ($([<T $i>]),+,)
where
$([<T $i>]: IntoIterator<Item = C>),+,
C: Borrow<Course>,
{
fn into_iter(self) -> impl Iterator<Item = C> {
IntoIterator::into_iter([])$(.chain(self.$i))*
}
}
}
};
}
Then we need:
impl_query!(0,);
impl_query!(0, 1,);
impl_query!(0, 1, 2);
impl_query!(0, 1, 2, 3);
impl_query!(0, 1, 2, 3, 4);
impl_query!(0, 1, 2, 3, 4, 5);
This is hard to write. So I tried:
macro_rules! gen_impl {
($macro: ident, $first: literal) => {
$macro!($first);
};
($macro: ident, $first: literal, $($i: literal),*$(,)?) => {
$macro!($first, $($i),*);
gen_impl!($macro, $($i),*);
};
}
gen_impl!(impl_query, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
Is there better method to do this? Or have there been any crate to help with this?
2 posts - 2 participants
🏷️ Rust_feed