(There are a million questions with a similar title but I think this one is distinct from them all.)
Rust version: 1.69.0.
The following works as expected:
fn main() {
println!("{}", format_args!("hello {}", "world"));
}
But the borrow checker prevents the following code from compiling.
fn main() {
let args = format_args!("hello {}", "world");
println!("{}", args);
}
The error:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:2:16
|
2 | let args = format_args!("hello {}", "world");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
3 | println!("{}", args);
| ---- 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
|
2 ~ let binding = format_args!("hello {}", "world");
3 ~ let args = binding;
|
I can't see any violations of Rust’s borrow rules — everything is in scope, bound to a variable, not dropped prematurely, etc., as far as I can tell. fmt::Arguments<'a> has a lifetime parameter but it's not clear what data it's trying to hold onto that is being dropped. Also, the help message is clearly bogus (args is exactly as long lived as binding would be!).
It's an known issue see #92698. For now we can't do that in Rust.
Related: Cannot use format_args! due to temporary value is freed at the end of this statement
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