0

我如何理解我违反了 Borrow Checker 的哪一部分?

因为 Rust 的标准库walk_dir列为“不稳定”(截至 2015-09-27),我想我会尝试构建自己的函数来获取目录中的所有文件,并且它是我自己的子目录。

这是我仅列出目录中的文件而不查看子目录部分的内容:

use std::fs::File;
use std::path::{Path,PathBuf};

fn get_files(this_path: &Path) -> Vec<&PathBuf>{
    let contents = fs::read_dir(this_path).unwrap();
    let mut output: Vec<&PathBuf> = Vec::new();

    for path in contents {
        let p = path.unwrap().path();
        if fs::metadata(&p).unwrap().is_dir() {
            // dunno, recursively append files to output 
        } else if fs::metadata(&p).unwrap().is_file() {
            output.push(&p)
        }
    }

    return output;
}

fn main() {
    for f in get_files(Path::new(".")) {
        println!("{}", f.display())
    }
}

当我尝试运行此代码时,我收到此错误:

src/main.rs:58:26: 58:27 error: `p` does not live long enough
src/main.rs:58             output.push(&p)
                                        ^
note: in expansion of for loop expansion
src/main.rs:53:5: 60:6 note: expansion site
src/main.rs:49:48: 63:2 note: reference must be valid for the anonymous lifetime #1 defined on the block at 49:47...
src/main.rs:49 fn get_files(this_path: &Path) -> Vec<&PathBuf>{
src/main.rs:50     let contents = fs::read_dir(this_path).unwrap();
src/main.rs:51     let mut output: Vec<&PathBuf> = Vec::new();
src/main.rs:52
src/main.rs:53     for path in contents {
src/main.rs:54         let p = path.unwrap().path();
               ...
src/main.rs:54:38: 60:6 note: ...but borrowed value is only valid for the block suffix following statement 0 at 54:37
src/main.rs:54         let p = path.unwrap().path();
src/main.rs:55         if fs::metadata(&p).unwrap().is_dir() {
src/main.rs:56             // dunno, recursively append files to output
src/main.rs:57         } else if fs::metadata(&p).unwrap().is_file() {
src/main.rs:58             output.push(&p)
src/main.rs:59         }
               ...
error: aborting due to previous error

如果我错了,请纠正我,但我的理解非常松散,Rust 的一个很酷的特性是你必须明确声明对象何时应该存在于函数范围之后。我认为我的问题是,在 for 循环的迭代结束时,PathBuf创建的那个被丢弃了,所以它持有对已经消失的东西的引用。let p = path.unwrap().path()output Vec

如果是这样的话:

当我在做这样愚蠢的事情时,如何建立更好的直觉?

有没有更好的惯用方法来从返回生命周期有限的资源的函数中构建元素向量?

4

1 回答 1

3

这里的直觉是:

我不能返回对函数内部创建的东西的引用,因为它将在该函数结束时被释放,从而使引用无效。

相反,您必须将其移出。因此Vec<PathBuf>, , 的拥有变体Vec<&PathBuf>(因为PathBuf, 的拥有变体&PathBuf)应该是您的返回类型。

于 2015-09-27T19:45:50.397 回答