A small marco to read data filed from Lines


#1

As a new learner, one of the most annoying task is to read data fields from stdio/file. Here is a small marco I wrote(with help from Chris Morgan, thank you so much) to make this task simple(at least for me).

macro_rules! read_tuple {
    (
        $lines:ident, ($($t:ty),*)
    ) => {{
        let l = $lines.next().unwrap();
        let mut ws = l.trim().split(" ");
        (
            $(ws.next().unwrap().parse::<$t>().unwrap(),)*
        )
    }}
}

you can simply use it as :

read_tuple!( "1 ab 3".lines()  ,(i32, String, i32))

results :

(1, "ab", 3)

there is anther two ,which might not as helpful as the read_tuple, is :

 macro_rules! read_item {
    ( $lines :ident , $t :ty ) => {{
      //  trace_macros!(true);
        ($lines).next().unwrap().unwrap().parse::<($t)>().unwrap()
    }}
}
macro_rules! read_vec {
    ( $lines :ident , $t :ty ) => {{
        //  trace_macros!(true);
        let ll =  ($lines).next().unwrap().unwrap().to_string();
        let sp = ll.split(' ');
        sp.map(| x  | x.parse::<($t)>().unwrap()).collect()
    }}
}

Splitting array into variables
#2

would you mind if I included this in https://github.com/oli-obk/rust-si ?

I’ll of course link to this thread and add an author note for you


#3

Yes, you can do what ever you like with this code.