PathBuf的寿命不够长

时间:2015-03-23 18:11:33

标签: rust lifetime

我正在尝试在构建脚本中使用以下代码:

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”,但为什么我的方法不起作用?

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

1 个答案:

答案 0 :(得分:4)

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

复制它的一个小例子是:

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

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

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

即可
panic!("{}", last_test);