How to convert a string to an enum?

限于喜欢 提交于 2019-12-22 08:06:26

问题


My original approach was to create method called to_str() which will return a slice, but I am not sure that it is correct approach because this code doesn't compile.

enum WSType {
    ACK,
    REQUEST,
    RESPONSE,
}

impl WSType {
    fn to_str(&self) -> &str {
        match self {
            ACK => "ACK",
            REQUEST => "REQUEST",
            RESPONSE => "RESPONSE",            
        }
    }
}

fn main() {
    let val = "ACK";
    // test
    match val {
        ACK.to_str() => println!("ack"),
        REQUEST.to_str() => println!("ack"),
        RESPONSE.to_str() => println!("ack"),
        _ => println!("unexpected"),
    }
}

回答1:


The correct thing is to implement FromStr. Here, I'm matching against the string literals that represent each enum variant:

#[derive(Debug)]
enum WSType {
    Ack,
    Request,
    Response,
}

impl std::str::FromStr for WSType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ACK" => Ok(WSType::Ack),
            "REQUEST" => Ok(WSType::Request),
            "RESPONSE" => Ok(WSType::Response),
            _ => Err(format!("'{}' is not a valid value for WSType", s)),
        }
    }
}

fn main() {
    let as_enum: WSType = "ACK".parse().unwrap();
    println!("{:?}", as_enum);

    let as_enum: WSType = "UNKNOWN".parse().unwrap();
    println!("{:?}", as_enum);
}

To print a value, implement Display or Debug (I've derived Debug here). Implementing Display also gives you .to_string().


In certain cases, there are crates that can reduce some of the tedium of this type of conversion. strum is one such crate:

use strum_macros::EnumString;

#[derive(Debug, EnumString)]
#[strum(serialize_all = "shouty_snake_case")]
enum WSType {
    Ack,
    Request,
    Response,
}


来源:https://stackoverflow.com/questions/36508580/how-to-convert-a-string-to-an-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!