enum Color {
Red,
Green,
Blue,
Yellow,
}
impl Color {
fn is_green(&self) -> bool {
if let Color::Green = self {
return true;
}
return false;
}
fn is_green_parts(&self) -> bool {
match self {
Color::Red => false,
Color::Blue => true,
Color::Yellow => true,
Color::Green => true,
}
}
}
fn print_color(color: Color) {
match color {
Color::Red => println!("Red"),
Color::Green => println!("Green"),
Color::Blue => println!("Blue"),
Color::Yellow => println!("Yellow"),
}
}
fn main() {
print_color(Color::Blue);
print_color(Color::Red);
print_color(Color::Green);
print_color(Color::Yellow);
let foo = Color::Green;
foo.is_green();
}
Cool thing about Enum in Rust, when you append a new enum value, for example Pink
, it will automatcilly tells you that in match
block, you missed Pink
.
In Typescript, there is no such benifits provdied automaticlly, it requires you doing something
enum Color {
Red,
Green,
Blue,
Yellow,
}
function main(color: Color) {
switch (color) {
case Color.Red:
console.log("red");
break;
case Color.Blue:
console.log("blue");
break;
case Color.Green:
console.log("green");
break;
default:
assertNever(color); // Error, you need to add case for Yellow
}
}
function assertNever(value: never) {
throw new Error(`Unexpected value: ${value}`);
}
标签:Blue,Color,Enum,Yellow,color,Green,Red,Rust From: https://www.cnblogs.com/Answer1215/p/17408764.html