注目の新言語Rustは半年くらい前まで仕様変更が激しすぎて学び甲斐がなかったが、最近は少しずつ仕様が安定してきているような印象。
Rust1.3でCSVを読み込む例。CSVライブラリはhttps://github.com/BurntSushi/rust-csvを使う。
read_csv.rs
extern crate csv;
extern crate rustc_serialize;
# [derive(RustcDecodable,Debug)]
struct MyRecord {
id: i32,
x: f32,
y: f32,
}
fn main() {
let mut rdr = csv::Reader::from_file("/path/to/file.csv").unwrap().has_headers(true);
let mut rows: Vec<MyRecord> = Vec::new();
for record in rdr.decode() {
if let Ok(r) = record {
rows.push(r);
}
}
println!("{:?}", rows);
}
-
csv::Reader::from_fileはResult型を返す。Result型はOkとErrorのenum。 -
unwrapはResultからOkを取り出す。-
Errorに対してunwrapするとエラー(パニック=スレッド停止)を起こす。
-
-
if letはパターンマッチに成功した時にブロック内の式を実行する。 - この例では、CSVの各行は
MyRecord型に自動で変換される。-
decode()は、rustc_serialize::Decodableトレイトを実装した型をResultで包んで返す。 - この例では、型推論により
MyRecordがResultに包まれた値を返す。 -
MyRecordは#[derive(RustcDecodable)]の指令によりDecodableを自動で実装
-