Rust's format_args!() lifetime
I recently had a desire to use the
format_args!()
macro
as an intermediate step to build up a formatted
Display
implementation.
If you run the above example you will get a failure:
--> src/main.rs:9:28
|
9 | let intermediate = format_args!("{something} World!");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
10 | write!(f, "{intermediate}")
| ------------ borrow later used here
|
= note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider using a `let` binding to create a longer lived value
|
9 ~ let binding = format_args!("{something} World!");
10 ~ let intermediate = binding;
|
Unfortunatly this suggestion is more or less what I had written:
let intermediate = format_args!("{something} World!");
Adding an extra intermediate variable will not help.
After banging my head for a while I finally ran across this issue
https://github.com/rust-lang/rust/issues/92698. The issue explained that
format_args!()
is meant to be used right away. It is temporary and is more or
less immediatly dropped.
This issue also explained that here are ways to work around this limitation by using match statements or similar: