(有很多类似标题的问题,但我认为这个问题与它们都不同。)
Rust 版本:1.69.0。
以下内容按预期工作:
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>
具有生命周期参数,但不清楚它试图保留什么数据正在被丢弃。此外,帮助信息显然是虚假的(args
的生命周期与binding
一样长!)。