Open
Description
openedon Jan 9, 2022
At the moment, we cannot store the result of a format_args!
in a value:
// Okay, we can somehow store it in a variable
let foo = format_args!("{} foo {:?}", 1, 2);
// But once we try to use it, we get
// "error[E0716]: temporary value dropped while borrowed"
// "note: consider using a `let` binding to create a longer lived value"
// "note: this error originates in the macro `format_args`"
println!("{}", foo);
// Using it directly is okay though
println!("{}", format_args!("{} foo {:?}", 1, 2));
// We can get pretty creative within the "direct usage" constraints :D
let foo = match format_args!("{} foo {:?}", 1, 2) {
foo => {println!("{}", foo);},
};
// But even if we manage to store the value in a struct, …
struct Foo<'a> {foo: std::fmt::Arguments<'a> }
let foo = Foo { foo: format_args!("{} foo {:?}", 1, 2) };
// … we still cannot make use of it outside of the scope it was created in
println!("{}", foo.foo); // <- error[E0716]: temporary value dropped while borrowed
The list of confused or annoyed users by this is rather long:
- format_args appears to be unusable #42253
- Try rethinking the format_args! macro #11838
- Using format_args!() to build a fmt::Arguments fails to compile #51905
- https://docs.rs/fern/0.6.0/fern/struct.FormatCallback.html
- https://stackoverflow.com/questions/56304313/cannot-use-format-args-due-to-temporary-value-is-freed-at-the-end-of-this-state
- https://users.rust-lang.org/t/using-format-args-and-log-builder/22695
- https://stackoverflow.com/questions/76157524/temporary-value-dropped-while-borrowed-when-printing-format-args
- https://internals.rust-lang.org/t/format-args-with-long-lifetimes/19494
I understand if the format_args!
macro cannot be changed, but then please provide an alternative way of building fmt::Arguments
without that restriction. Even a small performance overhead (for example cloning the values) would be an improvement compared to the common workarounds that have to be used otherwise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment