小编Ser*_*ey 的帖子

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

最初的方法是创建一个方法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"),
    }
}
Run Code Online (Sandbox Code Playgroud)

enums casting rust

4
推荐指数
1
解决办法
850
查看次数

标签 统计

casting ×1

enums ×1

rust ×1