I'm about 3/4 through the book and have enjoyed it, but I'm starting building some stuff on my own to use the language and get going. I have confused myself a little though . I'm trying to build on the cli example in the book, by building a cli that does some image transformations. I'm accepting 2 params initially from the cli, the filename and the action.
I only have 4 actions available currently, 1) Gray scale the image, 2) Thumbnail the image, 3) Rotate it, 4) Crop it.
I put these as part of an enum, and then wanted to take the action parameter from the CLI and confirm that the action given i.e "gray" was a valid action. I've included the code, my action_type
. I've confused myself as to how to do this, so wondered if someone could point me in the right direction. Or point out a better way to achieve this?
use std::error::Error;
// a lis tof available commands as an enum
pub enum ActionKind {
Gray(String),
Thumb(String),
Rotate(String),
Crop(String)
}
pub struct Config {
pub image_path: String,
pub action: ActionKind
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("Not enough arguments");
}
let image_path = args[1].clone();
let env_action = args[2].clone();
fn action_type(action: String) -> Option<ActionKind> {
match action {
a => ActionKind::Gray("gray"),
a => ActionKind::Thumb("thumb"),
a => ActionKind::Rotate("rotate"),
a => ActionKind::Crop("crop"),
_ => None,
}
}
let action = action_type(env_action);
Ok( Config{ image_path, action } )
}
}