“活得不够久"同一个函数中的错误 [英] "does not live long enough" error in same function

查看:20
本文介绍了“活得不够久"同一个函数中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这段代码能够工作,因为所有绑定都在同一范围内:

I expected this code to work because all bindings are in the same scope:

fn main() {
    let mut foobar = vec!["foo"];
    let bar = "bar".to_string();
    foobar.push(&bar);
}

但我收到此错误:

error: `bar` does not live long enough
 --> baz.rs:4:18
  |>
4 |>     foobar.push(&bar);
  |>                  ^^^
note: reference must be valid for the block suffix following statement 0 at 2:33...
 --> baz.rs:2:34
  |>
2 |>     let mut foobar = vec!["foo"];
  |>                                  ^
note: ...but borrowed value is only valid for the block suffix following statement 1 at 3:32
 --> baz.rs:3:33
  |>
3 |>     let bar = "bar".to_string();
  |>                                 ^

error: aborting due to previous error

推荐答案

在同一块中声明的变量的删除顺序与它们声明的顺序相反.在您的代码中, barfoobar 之前被删除:

Variables declared in the same block are dropped in the reverse order that they are declared. In your code, bar is dropped before foobar:

fn main() {
    let mut foobar = vec!["foo"]; // <---------| 0
    let bar = "bar".to_string();  // <--| 1    |
    foobar.push(&bar);            //    | bar  | foobar
                                  // <--|      |
                                  // <---------|
    // In the error message
    // 0 is called "block suffix following statement 0", and
    // 1 is called "block suffix following statement 1"
}

您正在将 reference 推送到 foobar 中的 bar,因此您必须确保 bar 位于至少与 foobar 一样长.但是因为bar是在foobar之后声明的,所以bar的生​​命周期实际上比foobar的生​​命周期短,也就是说foobar 包含一个短暂的悬空引用.

You are pushing a reference to bar in foobar, so you have to ensure that bar lives at least as long as foobar. But because bar is declared after foobar, bar's lifetime is actually shorter than foobar's, which means that foobar contains a dangling reference for a short moment.

为了编译代码,在foobar之前声明bar:

To make the code compile, declare bar before foobar:

fn main() {
    let bar = "bar".to_string();
    let mut foobar = vec!["foo"];
    foobar.push(&bar);
}

或选择非词法生命周期:

#![feature(nll)]

fn main() {
    let mut foobar = vec!["foo"];
    let bar = "bar".to_string();
    foobar.push(&bar);
}

虽然这仍然有一个悬空引用,但这并不重要,因为删除引用什么也不做;Vec 在删除时不需要使用它包含的引用的值.

Although this still has a dangling reference, it doesn't matter because dropping a reference does nothing; the Vec doesn't need to use the value of the references it contains when it's dropped.

这篇关于“活得不够久"同一个函数中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆