Using macro to parse list of option

I'm trying to create a macro that can parse a list of elements, including option or other type, and return Vec<Option<_>>.

macro_rules! elem {
    (None) => { None };
    (Some, (, ($e:expr), )) => { Some($e:expr) };
    ($e:expr) => { Some($e.to_owned()) };
}

macro_rules! vector {
    ($($e:tt),*) => {{
        vec![$(elem!($e)), *]
    }}
}

fn main() {
    // works
    println!("{:#?}", vector![1, 2, None, 3, 4, 5]);
    println!("{:#?}", vector!["1", "2", None, "3", "4", "5"]);
    
    // not work
    println!("{:#?}", vector![1, 2, None, 3, Some(4), 5]);
}

How can I match Some( val) and make the code work?

I would recommend this:

macro_rules! vector {
    ($($e:expr),*) => {
        vec![$(Option::from($e)),*]
    };
}

fn main() {
    println!("{:?}", vector![1, 2, None, 3, 4, 5]);
    println!("{:?}", vector!["1", "2", None, "3", "4", "5"]);
    println!("{:?}", vector![1, 2, None, 3, Some(4), 5]);
}
2 Likes

It works now. Thank you very much.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.