PathBuf 寿命不够长

PathBuf does not live long enough

我正在尝试让以下代码在构建脚本中运行:

use std::path::PathBuf;
use std::env;
use std::ffi::AsOsStr;

fn main() {
    let mut string = env::var("CARGO_MANIFEST_DIR").unwrap();
    let mut main_dir = PathBuf::new(string);
    main_dir.push("src/dependencies");

    let test_str = main_dir.as_os_str(); // test_str gets the same lifetime as main_dir

    let second_test = test_str.to_str();

    let last_test = second_test.unwrap();
    panic!(&last_test);
}

我收到以下错误:

<anon>:10:24: 10:32 error: `main_dir` does not live long enough
<anon>:10         let test_str = main_dir.as_os_str(); // test_str gets the same lifetime as main_dir
                                 ^~~~~~~~
note: reference must be valid for the static lifetime...
<anon>:7:48: 16:6 note: ...but borrowed value is only valid for the block suffix following statement 1 at 7:47
<anon>:7         let mut main_dir = PathBuf::new(string);
<anon>:8         main_dir.push("src/dependencies");
<anon>:9     
<anon>:10         let test_str = main_dir.as_os_str(); // test_str gets the same lifetime as main_dir
<anon>:11     
<anon>:12         let second_test = test_str.to_str();
          ...
<anon>:15:17: 15:26 error: `last_test` does not live long enough
<anon>:15         panic!(&last_test);
                          ^~~~~~~~~
<std macros>:1:1: 12:62 note: in expansion of panic!
<anon>:15:9: 15:28 note: expansion site
note: reference must be valid for the static lifetime...
<anon>:14:45: 16:6 note: ...but borrowed value is only valid for the block suffix following statement 5 at 14:44
<anon>:14         let last_test = second_test.unwrap();
<anon>:15         panic!(&last_test);
<anon>:16     }
error: aborting due to 2 previous errors

我实际上是将每个值都保存在一个自己的变量中。那么这怎么可能不超过声明呢?我知道也有 "into_os_string",但为什么我的方法不起作用?

我真的很想了解整个一生的事情,但这非常困难。也许有人可以快速浏览我的示例并告诉我每个语句中的生命周期发生了什么以及为什么它不起作用?这对我有很大帮助

注释掉代码行,我们可以发现失败的是panic!行。 panic! 的第一个参数应该是格式化字符串,它必须具有 'static 生命周期,因为它是实际编译的。

复制这个的一个小例子是:

let s = "Foo".to_string();
panic!(&s);

但出于某种原因,此示例有一条 更好的错误消息,指向 &s.

对于您的示例,您只需将 panic! 行更改为:

panic!("{}", last_test);