Skip to content

Instantly share code, notes, and snippets.

@vhbit
Created June 11, 2014 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vhbit/b95ea993ea62fbbba47e to your computer and use it in GitHub Desktop.
Save vhbit/b95ea993ea62fbbba47e to your computer and use it in GitHub Desktop.
Comment on error handling example
fn result_from_option<T, E>(a: Option<T>, f: || -> E) -> Result<T, E> {
match a {
Some(a) => Ok(a),
_ => Err(f())
}
}
fn slurp_file(file: &Path) -> Result<Vec<LabelPixel>, SlurpError> {
use std::{result, option};
let file: File = try!(File::open(file).map_err(|e| FailedIo(e)));
let mut file = BufferedReader::new(file);
let lines = file.lines()
.skip(1)
.map(|line| {
let line = try!(line.map_err(|e| FailedIo(e)));
let mut splits = line.as_slice().trim().split(',').map(|x| from_str(x));
// .and_then is flattening Option<Option<int>> to Option<int>.
let label: int = try!(result_from_option(splits.next().and_then(|x| x), || InvalidInput));
let pixels: Vec<int> = try!(result_from_option(option::collect(splits), || InvalidInput));
Ok(LabelPixel {
label: label,
pixels: pixels
})
});
result::collect(lines)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment