0

I wrote this code:

//Amazing log function that can take up to three parameters!!!
macro_rules! log {
        // todo variadic
        () => {
            let string = " ";
            info!(" ");
        };
        ($a:expr) => {
            let string = format!("{}", format_args!("{}", $a));
            info!("{}", string);
        };
        ($a:expr,$b:expr) => {
            let string = format!("{}", format_args!("{}{}", $a, $b));
            info!("{}", string);
        };
        ($a:expr,$b:expr,$c:expr) => {
            let string = format!("{}", format_args!("{}{}{}", $a, $b, $c));
            info!("{}", string);
        };
    }

Example usage:

    let number = 163.19;
    log!("Heeey fam is this number right: ", number, ". No, it's wrong");
    //output: [TIME INFO project] Hey fam is this number correct: 163.19. No, it's wrong

I want it to be able to take any number of parameters is that possible in rust?

Failure
  • 55
  • 8
  • I know about https://doc.rust-lang.org/rust-by-example/macros/variadics.html#variadic-interfaces but how do you implement it here? – Failure Jun 26 '22 at 14:39
  • Does this answer your question? [How can I create a function with a variable number of arguments?](https://stackoverflow.com/questions/28951503/how-can-i-create-a-function-with-a-variable-number-of-arguments) – user2722968 Jun 26 '22 at 15:12
  • thanks the second answer of that question helped. – Failure Jun 26 '22 at 16:05

1 Answers1

1

This is it.

macro_rules! log {
    ($($args:expr),*) => {
        let mut result: String = String::from("");
        $(
            let tempstr: String = format!("{}", format_args!("{}", $args));
            result.push_str(&tempstr[..]);
        )*
        info!("{}", result);
    };
}
Failure
  • 55
  • 8