Skip to content

Instantly share code, notes, and snippets.

Created January 4, 2017 16:01
Show Gist options
  • Save anonymous/aa8ef4cfac1270c9a0208e392afcfb3d to your computer and use it in GitHub Desktop.
Save anonymous/aa8ef4cfac1270c9a0208e392afcfb3d to your computer and use it in GitHub Desktop.
Shared via Rust Playground
trait Unpack<T> {
fn unpack<I: Iterator<Item=T>>(i: I) -> Self;
}
macro_rules! impl_unpack {
(@replace_ty $_t:tt $ty:ty ) => { $ty };
(@replace_expr $_t:tt $expr:expr) => { $expr };
(@expand $($ident:ident,)* ) => {
impl<T> Unpack<T> for (
$( impl_unpack!{ @replace_ty [$ident] Option<T> } ),*
) {
fn unpack<I: Iterator<Item=T>>(mut _i: I) -> Self {
(
$( impl_unpack!{ @replace_expr [$ident] _i.next() } ),*
)
}
}
};
() => {
impl_unpack!{ @expand }
};
($x:ident, ) => {
impl_unpack!{ @expand $x, }
impl_unpack!{ }
};
($x:ident, $($rest:ident,)* ) => {
impl_unpack!{ @expand $x, $($rest,)* }
impl_unpack!{ $($rest,)* }
}
}
impl_unpack!{ x, x, x, x, x, x, x, x, x, x, x, x, x, x, }
fn main() {
let (a, b, c, d) = Unpack::unpack(vec![1, 2].into_iter());
println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment