Include variable name in formatted string

Python 3.8 added a nice debug feature: by adding the = sign to the expression, it adds the expression itself to interpolated strings. [docs]

>>> my_variable=42
>>> print(f'{my_variable}')
42
>>> print(f'{my_variable=}')
my_variable=42

I haven't found anything similar in Rust. Has anything similar been considered yet? Would it be a useful feature? Is it worth writing an RFC for?

Example:

let my_variable=42;

// Current
println!("my_variable={my_variable}"); 
println!("my_variable={my_variable:05}");

// Proposed
println!("{my_variable=}");
println!("{my_variable=:05}");

dbg!(my_variable);

3 Likes

Rust already has the dbg! macro.

fn main() {
    let x = 10;
    dbg!(x);
}
[src/main.rs:3] x = 10
1 Like

Thank you both, The dbg! marco is certainly useful.

Python f-strings can be used for more complex logging and debug purposes, something that the dbg! macro doesn't cover:

print(f'Called with {param1=} {param2=} while having {someState=}')

Rust doesn't have that particular feature.

To answer your original question, I personally wouldn't make the effort to write an RFC for something like this. I don't think its impossible that it could be added to Rust (after all, we recently got the {var_name} syntax), but my guess is that it would be difficult to garner enough support to add it.

2 Likes

F-string syntax is cool, but not that important since most users are satisfied to have the handy subsets of it[1].


  1. if it was quite desired, the downloads of f-string crates wouldn't be low ↩︎

1 Like

You know what, I think this would actually be a nice addition. I know dbg! exists, but I often want to format multiple things on a line, or keep them in a compact format. I've probably written a "dump multiple variables" macro more than a dozen times. Since format strings are expanded at compile time, there shouldn't be any runtime overhead to supporting it.

I can't really think of a downside. Might make a good first contribution.

1 Like

FWIW, a quick and dirty way to print multiple values on the same line with dbg! is to pass them in a tuple: dbg!((foo, 42, bar(1.23))) (and for those who don’t know, note that dbg! can already take multiple parameters but prints them on separate lines, still can be handy).

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.