2 unstable releases

0.2.0 Jun 17, 2019
0.1.0 Feb 16, 2019

#1323 in Rust patterns

Download history 15/week @ 2023-08-12 16/week @ 2023-08-19 8/week @ 2023-08-26 13/week @ 2023-09-02 15/week @ 2023-09-09 12/week @ 2023-09-16 5/week @ 2023-09-23 11/week @ 2023-09-30 10/week @ 2023-10-07 14/week @ 2023-10-14 13/week @ 2023-10-21 17/week @ 2023-10-28 13/week @ 2023-11-04 11/week @ 2023-11-11 14/week @ 2023-11-18 21/week @ 2023-11-25

61 downloads per month
Used in jp_cli

MIT/Apache

7KB

exit crates.io badge

This crate exposes a type, Exit, which allows using ? in main while also specifying custom exit status codes.

The goal of this crate was to provide a proof of concept and sample implementation for the ideas discussed in this blog post.

Example

#![feature(try_trait)]
use exit::{Exit, ExitDisplay};

use std::env;
use std::option;

#[derive(Debug)]
enum MyErr {
    MissingArg,
    ParseErrorUserNum,
    ParseErrorGroupNum,
}

impl From<MyErr> for i32 {
    fn from(err: MyErr) -> Self {
        match err {
            MyErr::MissingArg => 2,
            MyErr::ParseErrorUserNum => 3,
            MyErr::ParseErrorGroupNum => 4,
        }
    }
}

// You can optionally implement ExitDisplay for your error type in order to print an error message
// on exit
impl ExitDisplay for MyErr {
    fn display(&self) -> String {
        format!("{:?}", self)
    }
}

impl From<option::NoneError> for MyErr {
    fn from(_: option::NoneError) -> Self {
        MyErr::MissingArg
    }
}

fn main() -> Exit<MyErr> {
    let user_num_string : String = env::args().skip(1).next()?;
    let group_num_string : String = env::args().skip(2).next()?;

    let user_num : u32 = user_num_string.parse()
        .map_err(|_| MyErr::ParseErrorUserNum)?;
    let group_num : u32 = group_num_string.parse()
        .map_err(|_| MyErr::ParseErrorGroupNum)?;

    println!("Hello, user #{} from group #{}!", user_num, group_num);

    Exit::Ok
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps