//-- ######################### //-- Task: Implementing early returns //-- Author: Vigneshwer.D //-- Version: 1.0.0 //-- Date: 26 March 17 //-- ######################### // Use `String` as our error type type Result = std::result::Result; fn double_first(vec: Vec<&str>) -> Result { // Convert the `Option` to a `Result` if there is a value. // Otherwise, provide an `Err` containing this `String`. let first = match vec.first() { Some(first) => first, None => return Err("Please use a vector with at least one element.".to_owned()) }; // Double the number inside if `parse` works fine. // Otherwise, map any errors that `parse` yields to `String`. match first.parse::() { Ok(i) => Ok(2 * i), Err(e) => Err(e.to_string()), } } fn print(result: Result) { match result { Ok(n) => println!("The first doubled is {}", n), Err(e) => println!("Error: {}", e), } } fn main() { let empty = vec![]; let strings = vec!["tofu", "93", "18"]; print(double_first(empty)); print(double_first(strings)); }