try and catch in rust

Solutions on MaxInterview for try and catch in rust by the best coders in the world

showing results for - "try and catch in rust"
Linus
05 Jun 2017
1use std::convert::TryFrom;
2
3struct GreaterThanZero(i32);
4
5impl TryFrom<i32> for GreaterThanZero {
6    type Error = &'static str;
7
8    fn try_from(value: i32) -> Result<Self, Self::Error> {
9        if value <= 0 {
10            Err("GreaterThanZero only accepts value superior than zero!")
11        } else {
12            Ok(GreaterThanZero(value))
13        }
14    }
15}
Benson
29 Nov 2020
1fn main() {
2    let do_steps = || -> Result<(), MyError> {
3        do_step_1()?;
4        do_step_2()?;
5        do_step_3()?;
6        Ok(())
7    };
8
9    if let Err(_err) = do_steps() {
10        println!("Failed to perform necessary steps");
11    }
12}
13