(有一百万个类似标题的问题,但我认为这一个与它们都不同。)
Rust版本:1.69.0.
以下内容按预期工作:
fn main() {
println!("{}", format_args!("hello {}", "world"));
}
但是借用检查器阻止编译以下代码。
fn main() {
let args = format_args!("hello {}", "world");
println!("{}", args);
}
错误:
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;
|
我看不出有任何违反Rust的借用规则的地方--据我所知,一切都在范围内,绑定到变量,没有过早地丢弃,等等。fmt::Arguments<'a>
有一个lifetime参数,但不清楚它试图保留的数据被丢弃。此外,帮助消息显然是伪造的(args
的寿命与binding
的寿命完全一样长!).
1条答案
按热度按时间xghobddn1#
这是一个已知问题,请参阅#92698。现在我们不能在Rust中这样做。
标签:Cannot use format_args! due to temporary value is freed at the end of this statement