rust 错误[E0515]:无法返回引用临时值的值(函数的返回值)

vwkv1x7d  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(169)

我无法解决我的代码的问题。我试图通过做一个项目来制作一个CLI应用程序来学习rust,我一直收到错误E0515
下面是我的代码:

use std::path::Display;
use std::fs;

fn read_file(path: &str) -> String {
    fs::read_to_string(path)
        .expect("Should have been able to read the file")
}

fn list_dir(path: &str) -> Vec<Display>{
    let paths = fs::read_dir(path).unwrap();
    let mut dirs: Vec<Display> = vec![];
    for path in paths {
        dirs.push(path.unwrap().path().display());
    }
    dirs
}

fn main() {
    println!("{}",list_dir("C:").len())
}

编译器告诉我,我返回了一个引用list_dir函数所拥有的数据的值:

error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:15:5
   |
13 |         dirs.push(path.unwrap().path().display());
   |                   -------------------- temporary value created here
14 |     }
15 |     dirs
   |     ^^^^ returns a value referencing data owned by the current function

我尝试了一些方法来改变函数的返回类型,但没有一个有效。
有人能告诉我我哪里做错了吗?

vq8itlhq

vq8itlhq1#

std::path::Display借用a Path。你可以告诉它,因为它在生命周期内是通用的(Display<'a>)。但你的问题更深。如果你尝试做这样的事情:

fn list_dir(path: &str) -> () {
    let paths = fs::read_dir(path).unwrap();
    let mut dirs: Vec<Display> = vec![];
    for path in paths {
        dirs.push(path.unwrap().path().display());
    }
}

这仍然会编译失败,你会得到以下错误:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:13:19
   |
13 |         dirs.push(path.unwrap().path().display());
   |         ----------^^^^^^^^^^^^^^^^^^^^------------ temporary value is freed at the end of this statement
   |         |         |
   |         |         creates a temporary value which is freed while still in use
   |         borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

这里的问题是fs::read_dir返回一个迭代器,它产生ReadDir结构,您可以使用方法ReadDir::path从其中获取PathBuf(OS路径的owned表示)。
但是,您不能存储对这些PathBuf的引用,因为它们将在下一次迭代中被删除
现在你要问自己,你想做什么?如果你想返回这些路径的向量(我猜这就是你想要的),只需返回Vec<PathBuf>。如果你想使用std::path::Display实现来获取路径的utf-8表示,返回一个String s的向量,然后在push调用中简单地调用to_string

相关问题