(有一百万个标题相似的问题,但我认为这个问题与所有问题都不一样。)
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
一样长寿!)。
这是一个已知问题,请参阅#92698。现在我们不能在 Rust 中做到这一点。