Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust `format!()` print `variable=value` like python's `f"{variable=}"

Tags:

format

rust

In python, I can include an = after a formatting parameter to print the value of the variable as well as the variable name:

var = 10
f"{var=}" # -> "var=10"

Is there a way to do this in Rust with the format!() macro? I know about the dbg! macro, but this string is going to a progress bar and dbg! doesn't return a string.

I'd like something like format!("{var:=}") or maybe format!("{var=}") but neither of those work.

To clarify, I'd like to not have to type the variable name, but still have it printed out. For example, if I'm printing out a long line of variables like:

println!("variable1={variable1}, variable2={variable2}, variable3={variable3}, variable4={variable4}");

Explicitly writing out the variable names gets old very quickly, and if I rename the variable then rust-analyzer doesn't pick up the string and will leave me with a situation like "old_name={new_name}".

It's a small thing, but I find f"{var1=}" super useful in python.

like image 867
beyarkay Avatar asked Aug 03 '26 07:08

beyarkay


1 Answers

I don't think there's anything like that in std or in the format! macro itself. If you just need the output similar to what dbg! does but as a String, you can write a simple macro for that:

macro_rules! my_format {
    ($val:expr $(,)?) => {
        format!("{} = {:#?}", stringify!($val), $val)
    }
}

fn main() {
    let value = 42;
    let s = my_format!(value);
    println!("{s}"); // prints out "value = 42"
}

You could even do it without a macro, with just a function. If you want to use it as a part of some longer string, you would have to resort to format!("My value: {}", my_format!(value)); though.

Playground

like image 54
Maxim Gritsenko Avatar answered Aug 07 '26 00:08

Maxim Gritsenko