我是Rust的新手并阅读了Rust编程语言,在错误处理部分有一个"案例研究",描述了一个程序,使用csv和rustc-serialize库(getopts用于参数解析)从CSV文件中读取数据.
作者编写了一个函数search,该函数使用一个csv::Reader对象逐步执行csv文件的行,并将那些"city"字段与指定值匹配的条目收集到一个向量中并返回它.我采取了与作者略有不同的方法,但这不应该影响我的问题.我的(工作)函数看起来像这样:
extern crate csv;
extern crate rustc_serialize;
use std::path::Path;
use std::fs::File;
fn search<P>(data_path: P, city: &str) -> Vec<DataRow>
where P: AsRef<Path>
{
let file = File::open(data_path).expect("Opening file failed!");
let mut reader = csv::Reader::from_reader(file).has_headers(true);
reader.decode()
.map(|row| row.expect("Failed decoding row"))
.filter(|row: &DataRow| row.city == city)
.collect()
}
Run Code Online (Sandbox Code Playgroud)
在DataRow类型仅仅是一个记录,
#[derive(Debug, RustcDecodable)]
struct DataRow {
country: String,
city: String,
accent_city: String,
region: String,
population: Option<u64>, …Run Code Online (Sandbox Code Playgroud)