You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust项目报错error[E0515]:无法返回引用临时值的返回值求解

解决Rust中的error[E0515]:返回引用临时值的问题

错误原因

你代码的核心问题出在Display类型的使用上:Path::display()返回的是一个临时引用类型(Display<'_>),它的生命周期完全依赖于生成它的Path实例。而循环中path.unwrap().path()创建的Path是临时对象,函数执行结束后会被立即销毁,你无法将这些绑定到临时对象的Display实例存入Vec并返回——这违反了Rust的内存安全规则,因此编译器抛出error[E0515]。

解决方案

有两种常用的修正方式,核心都是改用拥有所有权的类型来存储数据,避免引用临时对象:

方案1:返回PathBuf的Vec

PathBuf是拥有完整路径所有权的类型,返回后可以安全保留所有路径数据,需要显示时再调用display():

use std::fs;
use std::path::PathBuf;

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<PathBuf>{
    let paths = fs::read_dir(path).unwrap();
    let mut dirs: Vec<PathBuf> = vec![];
    for path in paths {
        dirs.push(path.unwrap().path());
    }
    dirs
}

fn main() {
    println!("{}", list_dir("C:").len());
    // 需要显示路径时再调用display()
    for path in list_dir("C:") {
        println!("{}", path.display());
    }
}

方案2:返回String的Vec

如果只需要路径的字符串形式,可以直接将Display的输出转换为String,同样是拥有所有权的类型:

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<String>{
    let paths = fs::read_dir(path).unwrap();
    let mut dirs: Vec<String> = vec![];
    for path in paths {
        let path_str = path.unwrap().path().display().to_string();
        dirs.push(path_str);
    }
    dirs
}

fn main() {
    println!("{}", list_dir("C:").len());
    for path in list_dir("C:") {
        println!("{}", path);
    }
}

总结

Rust禁止返回引用函数内部临时对象的值,本质是为了避免悬垂引用导致的内存不安全问题。改用PathBuf或String这类拥有所有权的类型,就能彻底解决这个错误。

内容的提问来源于stack exchange,提问作者Radinmsv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:54:51