rustrust-clippy

How to pretty-print inlined variables when formatting strings


Normally one can print strings the following way: println!("{:#?}", foo) where the {:#?} syntax will make a pretty-print of the value. But I know it's also possible to inline the variable directly in the string between the curly braces, instead of listing it as a second argument to the macro, like so: println!("{foo}").

My question is - can I combine the pretty-print syntax and inlining the variable in the string?

I found out about the shorthand syntax from clippy's docs, but I couldn't find (or understand) how to combine it with pretty-print (if it's at all possible).


Solution

  • Simply place the variable name before the colon:

    fn main() {
        let foo = 3;
        println!("{foo:#?}");
    }
    

    Note:

    Display is for user-facing output

    Debug is for output when debugging, also used for panic messages