-
-
Save matematikaadit/ff00dbeda1a1fabc6e77585740d853a5 to your computer and use it in GitHub Desktop.
Unpacking IntoIterator into Tuple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Unpack<T> { | |
fn unpack<I: IntoIterator<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: IntoIterator<Item=T>>(i: I) -> Self { | |
let mut _i = i.into_iter(); | |
( | |
$( 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(1..10); | |
println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment