为什么这个Rust功能不起作用?

时间:2016-04-24 03:21:59

标签: rust borrow-checker

我正在努力了解如何在Rust中做一些简单的事情,但我一直在与借阅检查器斗争,我不知道为什么。我编写了一个简单的函数,您可以在其中传递文件名,并为您提供主目录中该文件的路径。

以下是该计划:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int studentId=0;
   int.TryParse(GridView1.SelectedValue, out studentId);
   Response.Redirect("~/UpdateItem.aspx?id=" + studentId);
}

当我尝试构建它时,我收到此错误:

use std::env;

fn filename_in_homedir(filename: &str) -> Option<&str> {
    let mut homedir = match env::home_dir() {
        None => return None,
        Some(p) => p
    };  
    homedir.push(filename);
    homedir.to_str()
}

fn main() {
    match filename_in_homedir(".ssh/id_rsa.pub") {
        Some(s) => println!("{}", s), 
        None => println!("Oops can't get it")
    };  
}

我不明白为什么不起作用。如果$ cargo build Compiling homedir-test v0.1.0 (file:///home/user/code/homedir-test) src/main.rs:9:5: 9:12 error: `homedir` does not live long enough src/main.rs:9 homedir.to_str() ^~~~~~~ src/main.rs:3:56: 10:2 note: reference must be valid for the anonymous lifetime #1 defined on the block at 3:55... src/main.rs:3 fn filename_in_homedir(filename: &str) -> Option<&str> { src/main.rs:4 let mut homedir = match env::home_dir() { src/main.rs:5 None => return None, src/main.rs:6 Some(p) => p src/main.rs:7 }; src/main.rs:8 homedir.push(filename); ... src/main.rs:7:7: 10:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 7:6 src/main.rs: 7 }; src/main.rs: 8 homedir.push(filename); src/main.rs: 9 homedir.to_str() src/main.rs:10 } error: aborting due to previous error Could not compile `homedir-test`. 失败,则函数返回env::home_dir()。如果成功,则可变变量homedir获取其值(即None)。此时,std::path::PathBuf变量应归homedir范围所有。下一行修改filename_in_homedir以将文件名添加到结尾,这样可以正常工作。最后一行,调用homedirreturns.to_str()本身。

由于我最终返回指向Option<&str>内某处的&str,可能在homedir范围结束且filename_in_homedir被删除时,homedir也是这样,这就是为什么它会抛出这个错误?

如何修改此功能才能正常工作,以及我做错了什么?

1 个答案:

答案 0 :(得分:2)

  

由于我最终返回指向homedir内某处的&amp; str,可能当filename_in_homedir范围结束并且homedir被删除时,&amp; str也会这样做,这就是为什么它&#39;抛出这个错误?

这是正确的:您正在尝试返回指向filename_in_homedir堆栈帧所拥有的值的指针,该值将在返回后被删除,从而使指针无效。您需要返回String,而不是&str。这是一种方法:

use std::env;
use std::borrow::ToOwned;

fn filename_in_homedir(filename: &str) -> Option<String> {
    let mut homedir = match env::home_dir() {
        None => return None,
        Some(p) => p
    };  
    homedir.push(filename);
    homedir.to_str().map(ToOwned::to_owned)
}

fn main() {
    match filename_in_homedir(".ssh/id_rsa.pub") {
        Some(s) => println!("{}", s), 
        None => println!("Oops can't get it")
    };
}