Rust PathBuf活得不够长
我正在尝试使以下代码在生成脚本中工作:Rust PathBuf活得不够长,rust,lifetime,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 t
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
:10:24:10:32错误:'main_dir'寿命不够长
:10让test_str=main_dir.as_os_str();//test_str与main_dir具有相同的生存期
^~~~~~~~
注意:引用必须在静态生存期内有效。。。
:7:48:16:6注意:……但借用值仅对语句1后面7:47的块后缀有效
:7让mut main_dir=PathBuf::new(字符串);
:8主目录推送(“src/dependencies”);
:9
:10让test_str=main_dir.as_os_str();//test_str与main_dir具有相同的生存期
:11
:12让第二个测试=测试到第二个测试();
...
:15:17:15:26错误:'last_test'寿命不够长
:15恐慌!(&last_test);
^~~~~~~~~
:1:1:12:62注:在恐慌的扩张中!
:15:9:15:28注:扩展站点
注意:引用必须在静态生存期内有效。。。
:14:45:16:6注意:……但借用值仅对14:44语句5后面的块后缀有效
:14让最后一次测试=第二次测试。展开();
:15恐慌!(&last_test);
:16 }
错误:由于之前的两个错误而中止
我实际上是将每个值保存在自己的变量中。那么,这怎么可能不超过声明的寿命呢?我知道也有“into_os_string”,但为什么我的方法不起作用
我真的在努力理解这一生的事情,但这很难。也许有人可以快速浏览我的示例,告诉我每个语句中的生命周期发生了什么,以及为什么它不起作用?这对我注释出一行行代码会有很大帮助,我们可以发现这是
恐慌代码>失败的行。panic的第一个参数
应该是一个格式化字符串,在实际编译时,它必须具有的静态
生存期
复制这一点的一个小例子是:
let s = "Foo".to_string();
panic!(&s);
但出于某种原因,这个示例有一条更好的错误消息,它指向&s
例如,您可以更改panic代码>行到:
panic!("{}", last_test);
很抱歉,刚刚更新了用于playpen的代码;)好吧,这太简单了:我太执着于我没有意识到的一生的事情。再次感谢你的担心;真正糟糕的错误消息令人惊讶。我想看看我是否能弄明白为什么这里这么糟糕。我-我们将看看是否有更好的错误消息。