我試圖導入使用the csv
crate一個CSV文件,但問題是,有些字段包含非UTF8值,所以我得到一個運行時的恐慌:處理運行時的恐慌與嘗試宏
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Decode("Could not convert bytes \'FromUtf8Error { bytes: [75, 108, 105, 110, 63, 101, 107, 111, 118, 225], error: Utf8Error { valid_up_to: 9 } }\' to UTF-8.")', /home/rustbuild/src/rust-buildbot/slave/nightly-dist-rustc-linux/build/src/libcore/result.rs:729
這是我的代碼看起來像:
extern crate csv;
fn main() {
let mut rdr = csv::Reader::from_file("data.csv").unwrap();
for record in rdr.decode() {
let rec: Vec<String> = record.unwrap();
println!("{}", rec[0]);
}
}
我想錯誤處理是驚情不知何故,所以我在想,也許我應該用try!
宏是什麼?事情是這樣的:
let rec: Vec<String> = try!(record.unwrap());
當然,這是產生錯誤
error: the trait `rustc_serialize::serialize::Decodable` is not implemented for the type `core::result::Result<_, _>` [E0277]
什麼是正確的語法?
如果你想在編碼方面更健壯,'rust-encoding'應該有所幫助:https://lifthrasiir.github.io/rust-encoding/encoding/ ---或者,你可以解碼爲'Vec>'如果你只是想完全忽略編碼。 –
BurntSushi5