3.2 Enums

enum 키워드는 하나 혹은 몇 가지 서로 다른 변수형들로 이루어진 타입를 생성할 수 있게 한다. struct로서 유효한 변수형은 enum으로도 유효하다.

// .
#![allow(dead_code)]
// `enum` .
// , .:
// `Engineer != Scientist` `Height(i32) != Weight(i32)`.
// .
enum Person {
// `enum` `unit-like` ,
Engineer,
Scientist,
// ,
Height(i32),
Weight(i32),
// .
Info { name: String, height: i32 }
}
// `Person` enum .
fn inspect(p: Person) {
// `enum` . ()
// `match` .
match p {
Person::Engineer => println!("Is an engineer!"),
Person::Scientist => println!("Is a scientist!"),
// `enum` `i` .
Person::Height(i) => println!("Has a height of {}.", i),
Person::Weight(i) => println!("Has a weight of {}.", i),
// `Info` `name` `height` `Info` .
Person::Info { name, height } => {
println!("{} is {} tall!", name, height);
},
}
}
fn main() {
let person = Person::Height(18);
let amira = Person::Weight(10);
// `to_owned()` string `String` .
let dave = Person::Info { name: "Dave".to_owned(), height: 72 };
let rebecca = Person::Scientist;
let rohan = Person::Engineer;
inspect(person);
inspect(amira);
inspect(dave);
inspect(rebecca);
inspect(rohan);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

See also:

attributes, match, fn, and String

results matching ""

    No results matching ""