Cod*_*Lee 4 file-io enums numbers vector rust
我正在尝试将文件中的数字列表(每行都有一个数字)读入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>());
}
}
Run Code Online (Sandbox Code Playgroud)
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)
您可以调用枚举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)
| 归档时间: |
|
| 查看次数: |
3635 次 |
| 最近记录: |