Error
typeThis pattern is a way to manage errors when you have multiple kinds of failure that could occur during a single function. It has several distinct advantages:
Fail
can be thrown into the Error
type using the ?
operator.To use this pattern, all you need to do is return Result<_, Error>
from your functions:
use std::io; use std::io::BufRead; use failure::Error; use failure::err_msg; fn my_function() -> Result<(), Error> { let stdin = io::stdin(); for line in stdin.lock().lines() { let line = line?; if line.chars().all(|c| c.is_whitespace()) { break } if !line.starts_with("$") { return Err(format_err!("Input did not begin with `$`")); } println!("{}", &line[1..]); } Ok(()) }
This pattern is very effective when you know you will usually not need to destructure the error this function returns. For example:
There are two primary downsides to this pattern:
Error
type allocates. There are cases where this would be too expensive. In those cases you should use a custom failure.