0

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?

Naitik Mundra
  • 418
  • 3
  • 14
  • `format!` is macro, not a function. If you want that behaviour, you'll need to write a macro. – Peter Hall Oct 22 '22 at 21:19
  • @PeterHall my bad that is what I meant. I get that but how is the question. I will edit to make it clear that I understand the difference. – Naitik Mundra Oct 22 '22 at 21:22

1 Answers1

4

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);
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • I guess I need to read the book on the macros again because I tried to implement it anf failed miserably. – Naitik Mundra Oct 22 '22 at 21:32
  • But, if I wanted to, could I wrap it in a function like so: `fn log2(x: T) {log!(x)}`. If so, what would `T` be? – Naitik Mundra Oct 22 '22 at 21:34
  • Perhaps you could look at the source of the [log crate](https://crates.io/crates/log) for inspiration. – Peter Hall Oct 22 '22 at 21:41
  • Also found https://stackoverflow.com/questions/28951503/how-can-i-create-a-function-with-a-variable-number-of-arguments.(just documenting for future use) Thanks for the help. – Naitik Mundra Oct 23 '22 at 06:47