열거형
이해
- 기본 문법
// 기본 선언 enum IpAddrKind { V4, V6, } // 기본 사용 let four = IpAddrKind::V4; let six = IpAddrKind::V6; // struct에 사용할 수 있음 struct IpAddr { kind: IpAddrKind, address: String, } // struct를 포함한 서로 다른 Type을 포함할 수 있음 enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); struct Ipv4Addr { // --snip-- } struct Ipv6Addr { // --snip-- } enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } // struct와 마찬가지로 impl 지원 impl Message { fn call(&self) { // method body would be defined here } } - match와 함께 사용
match는 가능한 모든 열거형 값을 포함해야 합니다.
가능한 모든 열거형 값을 나열하지 않을 때는 다른 변수나 밑줄로 대신할 수 있습니다.
match 문이 반환하는 값의 Type은 일치해야 합니다.
match도 move를 발생시킨다는 점에 유의하세요.
match의 다른 사용 방식은 다른 장에서 설명합니다.
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } #[derive(Debug)] enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, // 한 줄이면 {}를 생략할 수 있음 Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter(state) => { // 여기의 값은 UsState::Alabama 또는 UsState::Alaska일 수 있음 println!("State quarter from {:?}!", state); 25 } }; match coin { Coin::Penny => 1, // 다른 경우를 나타내는 다른 변수를 사용할 수 있음 a => { println!("{:?}", a); 5 }, }; match coin { Coin::Penny => 1, // 밑줄을 사용할 수 있음 _ => 5, } } - if let과 함께 사용
let mut count = 0; // match 写法 match coin { Coin::Quarter(state) => println!("State quarter from {:?}!", state), _ => count += 1, } // if let 写法 if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; }