(有一百万个问题有类似的标题,但我认为这个问题与所有问题都不同.)

铁 rust 版本:1.69.0.

以下内容的工作方式与预期一致:

fn main() {
    println!("{}", format_args!("hello {}", "world"));
}

但borrow 判断器会阻止编译以下代码.

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 做到这一点.

相关:Cannot use format_args! due to temporary value is freed at the end of this statement

Rust相关问答推荐

包含嵌套 struct 的CSV

将大小为零的类型实例存储到空指针中

限制未使用的泛型导致编译错误

如何实现泛型枚举的`Serde::Desialize`特性

在Rust中,在实现特征`Display`时,如何获取调用方指定的格式?

我应该将哪些文件放入我的GitHub存储库

完全匹配包含大小写的整数范围(&Q;)

在macro_rule中拆分模块和函数名

如何实现Deref;多次;?

为什么rustc会自动降级其版本?

这是什么:`impl Trait for T {}`?

为什么我们有两种方法来包含 serde_derive?

如何将 C++ 程序链接到 Rust 程序,然后将该 Rust 程序链接回 C++ 程序? (cpp -> rust -> cpp)

在不安全的 Rust 中存储对 struct 内部数据的静态引用是否合法?

Rust 中的方法调用有什么区别?

SDL2 没有在终端键上触发?

当我在 struct 中存储异步函数时,为什么它需要生命周期

Rust,我如何正确释放堆分配的内存?

从函数返回 u32 的数组/切片

Rust 中的运行时插件