rust 提取分配给向量的文件行

bvk5enib  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(118)

玩弄铁 rust ,陷入一个基本的分配错误。
下面是我的代码:

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`

我知道我的scopes are off,但不知道为什么-这是漫长的一天🥹
谢谢!

dgjrabp2

dgjrabp21#

std::io::Lines生成拥有的String,而不是借用的&str,因此您不能删除它们并将对它们的引用存储在Vec中。
而是将拥有的String存储在Vec

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)
            }
            Err(_) => todo!(),
        })
    }

    return file_lines;
}

相关问题