如何将CLI参数限制为枚举?

时间:2016-10-22 21:20:50

标签: enums rust

在学习Rust并尝试做一些有用的事情时,我正在寻找SAFE API call for DNS:Add service。 API定义明确,并且权利应该是一个简单的PUT请求,其主体是一些字符串和一个限制为两个选项的变量。

我已经看过为它的实体限制定义一个结构和枚举,而不仅仅是使用字符串;正如我期望定义接近现实,是更好的实践。

我认为我必须接近然后才会出现不匹配,试图将输入限制为枚举。第三个论点应该只是' drive'或者' app'为RootPathVariant

所以,我希望为root_path分配arguments=arg[2]的匹配项 但是atm匹配的左侧是&'static str,这在需要String的地方是错误的。

枚举定义为:

pub enum RootPathVariant { App, Drive }

impl RootPathVariant {
    pub fn as_str(&self) -> &str {
        match self {
            &RootPathVariant::App => "app",
            &RootPathVariant::Drive => "drive",
        }
    }
}

我应该如何放置此匹配的左侧,仅接受该枚举的内容?

let mut root_path: RootPathVariant = RootPathVariant::Drive;
match args[2].to_string() {
    "drive" => { root_path = RootPathVariant::Drive },
    "app" => { root_path = RootPathVariant::App },
    _ => { println!( "Error: root_path not [drive | app]");  return }
};

let put_body = AddServiceBody {
    long_Name: args[0],
    service_Name: args[1],
    root_Path: root_path,
    service_Home_Dir_Path: args[3]
};

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

注意答案似乎是match args[2].as_str()