My rust macro doesn't want to accept this let statement

368 Views Asked by At

I've been trying to make a macro that functions similar to Python's input function.

Rather than write the stdin completely every time I wanted to automate it somewhat, and combine println! so I could kill 2 birds with one stone.

Essenitally, if someone passes in an argument it'll print a string then ask for input, if they don't it will just ask for input from the terminal.

#[macro_export]
macro_rules! input {
    ($a:expr) => {
        println!("{}", $a);
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();

        return $input
    };

    (_) => {
        let mut input = String::new();
        std::io::stdin().read_line(&mut $input).unwrap();

        return $input
    };
}

I keep getting an error on the let statement and just don't know how to continue because I don't know the macro syntax well.

I posted the whole code block beacuse on the second match expression I was trying to make a match for when there were no arguments but i'm not sure if I did it correctly.

Sometimes the error messages brought me to github pages and I encounter randomed bugs, so i'm just confused how to continue furhter

It would be most appreciated if someone could help me fix the let statement, and i'd like to apologize for any inconvience.

1

There are 1 best solutions below

3
On BEST ANSWER
#[macro_export]
macro_rules! input {
    ($a:expr) => {{
        println!("{}", $a);
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        input
    }};

    (_) => {{
        let mut input = String::new();
        std::io::stdin().read_line(&mut $input).unwrap();

        input
    }};
}

fn main() {
    let foo = input!("Blargh");
}

You need the extra curly braces. The first pair is to enclose what the macro should expand to. The second pair is because the macro should expand to a code block.

Then we get rid of return because a macro isn't a function. Instead, it just expands to some code, and the value of a code block is just the last expression (without a ;).