Skip to content

Instantly share code, notes, and snippets.

@gyu-don
Created August 15, 2017 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gyu-don/c943688bc916749f5af3050c366ac9e5 to your computer and use it in GitHub Desktop.
Save gyu-don/c943688bc916749f5af3050c366ac9e5 to your computer and use it in GitHub Desktop.
Rust macro for making variables from a iterator.
macro_rules! let_from_iter {
($($a:ident),+ = $it:expr) => {
$(let $a;)+
{
let mut _it = $it.into_iter();
$($a = _it.next().unwrap();)+
assert!(_it.next().is_none());
}
};
}
fn main() {
let v = vec![1];
let_from_iter!(a = v);
println!("{}", a);
let v = vec![1,2,3,4];
let_from_iter!(b, c, d, e = v.iter());
println!("{} {} {} {}", b, c, d, e);
let v = vec![1,2];
let_from_iter!(a = v); // should panic.
println!("{}", a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment