mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-15 18:12:43 +00:00
50 lines
1.1 KiB
Rust
50 lines
1.1 KiB
Rust
// ./src/error/multiple_error_types/reenter_question_mark.md
|
|
|
|
|
|
use std::error;
|
|
use std::fmt;
|
|
|
|
// Change the alias to `Box<dyn error::Error>`.
|
|
type Result<T> = std::result::Result<T, Box<dyn error::Error>>;
|
|
|
|
#[derive(Debug)]
|
|
struct EmptyVec;
|
|
|
|
impl fmt::Display for EmptyVec {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(f, "invalid first item to double")
|
|
}
|
|
}
|
|
|
|
impl error::Error for EmptyVec {}
|
|
|
|
// The same structure as before but rather than chain all `Results`
|
|
// and `Options` along, we `?` to get the inner value out immediately.
|
|
fn double_first(vec: Vec<&str>) -> Result<i32> {
|
|
let first = vec.first().ok_or(EmptyVec)?;
|
|
let parsed = first.parse::<i32>()?;
|
|
Ok(2 * parsed)
|
|
}
|
|
|
|
fn print(result: Result<i32>) {
|
|
match result {
|
|
Ok(n) => println!("The first doubled is {}", n),
|
|
Err(e) => println!("Error: {}", e),
|
|
}
|
|
}
|
|
|
|
fn part0() {
|
|
let numbers = vec!["42", "93", "18"];
|
|
let empty = vec![];
|
|
let strings = vec!["tofu", "93", "18"];
|
|
|
|
print(double_first(numbers));
|
|
print(double_first(empty));
|
|
print(double_first(strings));
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|