rust 打印`format_args!时借用时丢失的临时值”

gijlo24d  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(149)

(有一百万个类似标题的问题,但我认为这一个与它们都不同。)
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的寿命完全一样长!).

相关问题