2016-04-08 42 views
3

我的original approach是創建一個名爲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"), 
    } 
} 
+0

@Shepmaster是的,你是對的,它不會編譯。我想我應該在原文中提及它。我試圖將隨機字符串切片與特定枚舉相匹配。 – Sergey

回答

9

正確的做法是實施FromStr

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

impl std::str::FromStr for WSType { 
    type Err = &'static str; 

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

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

要打印值,實現DisplayDebug(我在這裏得到的話)。實施Display也會給你.to_string()

+0

謝謝@Shepmaster,它看起來很完美。 – Sergey