Home > Net >  How to write a function that accepts an argument similar to format!() in rust
How to write a function that accepts an argument similar to format!() in rust

Time:10-24

Let us say I have a function like follows:

fn log(msg: &str) {
    //fancy_output
    println!("{}", msg)
}

Now, if I want to log a variable using the function, I must do it like so:

let x = 5;
log(&format!("{:?}", x)); // Assume some complex data type which implements Debug

Clearly this is a lot of boilerplate. I could remove the & by making the argument a string, but that does not remove my bigger problem: using format!() everywhere.

How can I write a function/macro such that I can do the following or similar:

let x = 5;
log("{:?}", x) // Assume some complex data type which implements Debug

I know a place to start would be looking at the format! source code, but it is quite hard to understand for a beginner like me and how I might implement it here.

Do I use some fancy macro or is there a simpler way?

CodePudding user response:

format! is a macro, not a function, which is why it is able to work with variable number of arguments. You can do the same with a declarative macro like this:

macro_rules! log {
    ($($args: tt)*) => {
        println!($($args)*);
    }
}

The $($args: tt)* means that the macro accepts zero or more (*) of any kind of token (tt). Then it just passes these on to the println macro.

Which you can call like this:

fn main() {
    let x = 5;
    log!("{:?}", x);
}
  • Related