首页 > 解决方案 > 如何将文件中的数字列表读入 Vec?

问题描述

我正在尝试将文件中的数字列表(每行都有一个数字)读入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>());
    }
}
  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());
}

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

标签: vectorrustfile-ioenumsnumbers

解决方案


您可以在枚举上调用该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();
}

操场


推荐阅读