【发布时间】:2015-06-02 23:20:27
【问题描述】:
我正在尝试读取和解析 Rust 中的文本文件。每行都是一个有符号整数。我可以使用for line in lines 迭代来做到这一点,但我无法使用iter().map(|l| ...) 单线来做到这一点。我得到了一个
expected `&core::result::Result<collections::string::String, std::io::error::Error>`,
found `core::result::Result<_, _>`
当我尝试对Ok(s) => match s.parse() 进行模式匹配时,但我无法深入了解我做错了什么。整个例子如下。底部的代码是产生错误的代码。
谁能告诉我我做错了什么?
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// Create a path to the desired file
let path = Path::new("input/numbers.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
// Collect all lines into a vector
let reader = BufReader::new(file);
let lines: Vec<_> = reader.lines().collect();
// Works.
let mut nums = vec![];
for l in lines {
println!("{:?}", l);
let num = match l {
Ok(s) => match s.parse() {
Ok(i) => i,
Err(_) => 0
},
Err(_) => 0
};
nums.push(num);
}
// Doesn't work!
let nums: Vec<i64> = lines.iter().map(|l| match l {
Ok(s) => match s.parse() {
Ok(i) => i,
Err(_) => 0
},
Err(_) => 0
});
}
【问题讨论】: