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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With