0

in c++ I used this:


    /** Amazing log method*/
    template<typename... Args>
    void inline log(Args const&... args)
    {
        std::string result;

        std::ostringstream stream;
        using List= int[];
        (void)List{0, ( (void)(stream << args), 0 ) ... };
        result = stream.str();

        result = "[LOG] " + result;
        
        //prints and writes string to log file with timestamp.
        logg(result);
    }
    //example usage:
    log("The final number is not: ", 12,", it's: ", 136.0f)
    //outputs: [TIME] The final number is not: 12, it's: 136.0f

Is it possible to write something similar in rust with variadics? How would you turn all parameters of any primitive type into string?

Failure
  • 55
  • 8
  • 2
    Rust's `print!` macro is capable of that, but the actual implementation is in `format_args!` and compiler-builtin. But you can write such macros yourself, see [Rust by Example](https://doc.rust-lang.org/rust-by-example/macros/variadics.html). – Caesar Jun 26 '22 at 13:08
  • https://stackoverflow.com/questions/28951503/how-can-i-create-a-function-with-a-variable-number-of-arguments – Marko Taht Jun 26 '22 at 13:10
  • To add to @Caesar's remark: It's not possible when you use a function, as functions in Rust must have a very clear signature. That's why `println` for example is a macro. But don't be fooled, macros in Rust are nothing like the preprocessor in C++, they are much safer and more powerful. – Finomnis Jun 26 '22 at 13:13
  • Also in case this is an XY problem: For logging, there is the [`log`](https://docs.rs/log/latest/log/) crate in Rust. It's a generic log adapter that can serve a bunch of different backends. My backend of choice is [`env_logger`](https://docs.rs/env_logger/latest/env_logger/). Note how all of the logging functions are macros, for the reasons discussed in the previous comments. – Finomnis Jun 26 '22 at 13:19
  • Well, thanks everyone. Good to know there's a log crate. And format_args! was indeed what I was looking for! But I still don't understand how to turn my current macro into a variadic macro. Have a look if you want: https://stackoverflow.com/questions/72762487/how-to-turn-the-following-macro-into-a-variadic – Failure Jun 26 '22 at 14:33

0 Answers0