Anatomy of a Rust Program, Part IV: /src/helperror.rs

This blog post is the fourth in a series that describes the structure of the wink command line program that I have written in rust and that I use to invoke other Windows and Linux programs from bash and Windows shells under Windows Subsystem for Linux. This post describes the HelpError struct used to indicate why the wink program should render usage information and exit, defined in the /src/helperror.rs file and hence crate::helperror:HelpError.

In some cases when the wink program should render usage information and exit, it creates an instance of the HelpError struct to indicate why.

The first line implements features that support formatting debugging messages for the type.

#[derive(Debug)]

The structure contains a single string field for a helpful message and an implementation that includes a new() function for use as a constructor, a fmt() function that formats the value of the struct for debugging purposes, and a description() function that enables use of this type as something like a derivative of std::error::Error.

#[derive(Debug)]
pub struct HelpError {
    pub message: String,
}

impl HelpError {
    pub fn new(msg: String) -> HelpError {
        HelpError { message: msg }
    }
}

impl std::fmt::Display for HelpError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for HelpError {
    fn description(&self) -> &str {
        &self.message
    }
}

2 thoughts on “Anatomy of a Rust Program, Part IV: /src/helperror.rs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: