如何将文件中的数字列表读入 Vec?

Cod*_*Lee 4 file-io enums numbers vector rust

我正在尝试将文件中的数字列表(每行都有一个数字)读入Vec<i64>Rust 中。我可以使用BufReader. 但是,我似乎无法从Result. 包裹的枚举中获取字符串的值BufReader

那么如何获取这些值进行Result解析,以便它们可以Vec用字符串以外的另一种类型填充 a 呢?

我尝试过的:

  1. 使用一个for循环,我可以打印这些值来证明它们在那里,但是当我尝试使用该行进行编译时,它会在解析时出现恐慌numbers.append(...)
fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);
    let numbers: Vec<i64> = Vec::new();

    for line in reader.lines() {
        // prints just fine
        println!("line: {:?}", line);
        numbers.append(line.unwrap().parse::<i64>());
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 或者,我尝试进行映射,但在将值放入Vec<i64>我要填充的值时遇到了同样的问题。
fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);

    let numbers: Vec<i64> = reader
        .lines()
        .map(|line| line.unwrap().parse::<i64>().collect());
}
Run Code Online (Sandbox Code Playgroud)

这不能仅仅通过如何在 Rust 中进行错误处理以及常见的陷阱是什么来解决。

kfe*_*v91 6

您可以调用枚举unwrap()上的方法Result来从中获取值。固定示例:

use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;

fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);

    let numbers: Vec<i64> = reader
        .lines()
        .map(|line| line.unwrap().parse::<i64>().unwrap())
        .collect();
}
Run Code Online (Sandbox Code Playgroud)

操场

  • @CoderLee `.lines()` 适用于任何缓冲读取器,这意味着个别行可能会因 IO 原因而失败。将字符串解析为 i64 也可能会失败。由于它们都容易出错,因此它们都返回必须处理的“Result”(在本例中通过“.unwrap()”) (4认同)