vector - 如何将文件中的数字列表读入 Vec?
问题描述
我正在尝试将文件中的数字列表(每行都有一个数字)读入Vec<i64>
Rust 中。我可以使用BufReader
. 但是,我似乎无法从Result
它们被BufReader
.
那么如何将这些值从Result
解析中提取出来,以便它们可以Vec
使用字符串以外的另一种类型填充 a 呢?
我试过的:
- 使用一个
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>());
}
}
- 或者,我尝试了映射,但是在将值放入
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());
}
解决方案
您可以在枚举上调用该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();
}
推荐阅读
- html - 我的样式表不适用于我的代码的某些部分
- swift - 为什么我不能在 self 是一个类的协议扩展中更改变量?
- c# - 将 JSON 数组反序列化为列表
- linker - 在链接时将来自多个目标文件的符号连接到一个表(例如 vtable)中
- c++ - 在 gdb 中显示当前函数的调用函数
- php - Laravel 使用 cpanel 通过共享主机发送电子邮件 - 失败
- awk - 如果使用 awk 在文件中找到匹配项,则在匹配后打印第 n 行的第 m 列
- netlogo - 如何使海龟根据彼此之间不同的间隔间隔表现出不同的行为?
- google-cloud-platform - 架构帮助 - ETL 数据流和处理的替代方案
- image - imagemagick 将图像裁剪为 pdf:pdf 保持裁剪尺寸