Elegant way to map error message to error enum in rust?

  Kiến thức lập trình

I’m new to Rust and I’m writing my version of xxd.

There’s the cli module in cli.rs:

use std::env;

pub enum ArgumentError {
    TooManyArguments
}

#[derive(Debug)]
pub enum InputType {
    FILE(String),
    INPUT
}


pub fn get_args() -> Result<InputType, ArgumentError>{
    let args: Vec<String> = env::args().collect();
    
    match args.len() {
        0 => Ok(InputType::INPUT),
        1 => Ok(InputType::FILE(args[0])),
        _ => Err(ArgumentError::TooManyArguments)
    }
}

In main.rs I have the following code:

enum MyXXDError {
    TooManyArguments(&'static str),
}


fn get_file() -> Result<cli::InputType, MyXXDError> {
    let args = cli::get_args();

    match args {
        Ok(input_type) => Ok(input_type),
        Err(error) => Err(
            match error {
                ArgumentError::TooManyArguments => MyXXDError::TooManyArguments("Too many arguments inserted.")
            }
        )
    }
}

My question is, how can I print the error message of the MyXXDError in a way that would work on every enum value I could add in the future (Assuming every future enum element would contain a &str)?

3

LEAVE A COMMENT