Skip to content

Instantly share code, notes, and snippets.

@max6cn
Created July 26, 2019 00:15
Show Gist options
  • Save max6cn/c78fc6f4faf4e000bc11a7494445b4b5 to your computer and use it in GitHub Desktop.
Save max6cn/c78fc6f4faf4e000bc11a7494445b4b5 to your computer and use it in GitHub Desktop.
Reading tuple from a line
// Reading tuple from a line
// Example : read_tuple( "1 ab 3"
// ,(i32, String, i32))
// Expected : (1, "ab", 3)
macro_rules! read_tuple {
(
$input:ident, ($($t:ty),*)
) => {
{
let mut ws = $input.trim().split(" ");
(
$(ws.next().unwrap().parse::<$t>(),)*
)
}
}
}
fn main() {
let _x = "1 ab 3";
let a = read_tuple!( _x, (i32, String, i32));
print!("{:?}",a);
}
@max6cn
Copy link
Author

max6cn commented Jul 26, 2019

if need a default value in case it goes wrong, then

macro_rules! read_tuple2 {
    ( $input:ident, ($($t:ty),*) ) => { {
        let mut ws = $input.trim().split(" ");
        (  $(ws.next().unwrap().parse::<$t>().unwrap_or(Default::default()),)*   )
    }}
}

fn main() {
    let  _x = "1 ab true";
    let a  = read_tuple2!( _x, (i32, String, bool));

    print!("{:?}",a);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment