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

Rust提取文件行到Vec<&str>时遇E0597生命周期错误求助

解决Rust中l does not live long enough生命周期错误

在实现从文件提取行到向量的功能时,遇到如下生命周期错误,代码及错误信息如下:

原代码

use std::fs::File;
use std::io::{self, BufRead};

fn parse_file_lines(filename: &str) -> Vec<&str> {
    let mut file_lines: Vec<&str> = Vec::new();
    if let Ok(lines) = read_lines(filename) {
        lines.for_each(|line| match line {
            Ok(l) => {
                // perform some logic here...
                file_lines.push(&l)
            }
            Err(_) => todo!(),
        })
    }

    return file_lines;
}

fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

编译器错误

error[E0597]: `l` does not live long enough
  --> src/main.rs:17:38
   |
14 |     let mut file_lines: Vec<&str> = Vec::new();
   |         -------------- lifetime `'1` appears in the type of `file_lines`
...
17 |             Ok(l) => file_lines.push(&l),
   |                      ----------------^^-
   |                      |               | |
   |                      |               | `l` dropped here while still borrowed
   |                      |               borrowed value does not live long enough
   |                      argument requires that `l` is borrowed for `'1`

错误原因

l是lines()返回的String类型,它的生命周期仅存在于当前的Ok(l)分支闭包内。当闭包执行完毕,l会被自动销毁。但你试图将&l(l的引用)存入file_lines向量,而file_lines作为函数返回值,其生命周期要覆盖整个函数调用周期。编译器不允许引用一个已经被销毁的值,因此抛出生命周期错误。

解决方案

将返回类型从Vec<&str>改为Vec<String>,直接存储拥有所有权的String而非引用。这样l的所有权会转移到向量中,不会有生命周期问题:

use std::fs::File;
use std::io::{self, BufRead};

fn parse_file_lines(filename: &str) -> Vec<String> {
    let mut file_lines: Vec<String> = Vec::new();
    if let Ok(lines) = read_lines(filename) {
        lines.for_each(|line| match line {
            Ok(l) => {
                // perform some logic here...
                file_lines.push(l) // 直接存入String,转移所有权
            }
            Err(_) => todo!(),
        })
    }

    file_lines
}

fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

补充说明

如果你的场景中确实需要使用字符串引用,必须保证被引用的字符串拥有足够长的生命周期(比如在函数外创建并传入),但在读取文件行的场景下,直接存储String是最合理的选择——因为文件行内容是动态读取的,无法在函数外预先创建,必须由函数内部持有所有权。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:45:35