如何将字符串转换为枚举类型?

9

我的原始方法是创建一个名为to_str()的方法,它将返回一个切片,但我不确定这是否是正确的方法,因为此代码无法编译。

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"),
    }
}

@Shepmaster 是的,你说得对,它无法编译。我想我应该在原始帖子中提到这一点。我尝试将随机字符串片段与特定的枚举进行匹配。 - Sergey
1个回答

20

正确的做法是实现FromStr。在这里,我匹配代表每个枚举变体的字符串文本:

#[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);
}

要打印一个值,请实现Display或者Debug(我在这里派生了Debug)。实现Display还会赋予你.to_string()


在某些情况下,有一些crate可以减少此类转换的某些繁琐过程。strum就是这样一个crate:

use strum_macros::EnumString;

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

谢谢@Shepmaster,看起来完美。 - Sergey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接