枚举类型
枚举类型通过列举可能值来定义新类型。与传统枚举不同,MoonBit的枚举类型允许每个枚举项关联数据。我们将每个枚举项称为枚举构造器。
本示例中定义的Color
枚举包含五个构造器:Red
、Green
、Blue
、RGB
和CMYK
。其中Red
、Green
和Blue
直接表示颜色值,而RGB
和CMYK
构造器则携带关联数据。
Red
和RGB(255,255,255)
都属于Color
类型的实例。如需显式创建实例,可采用类似结构体的Color::Red
语法。
在print_color
函数中,我们使用模式匹配来区分不同的枚举构造器。这种控制流类似于C系语言中的switch-case语句,不同之处在于:可以通过在=>
左侧为关联数据命名,并在右侧作为变量使用这些数据。
我们将在后续章节深入探讨模式匹配的更强大功能。
enum Color {
Red
Green
Blue
RGB(Int, Int, Int)
CMYK(Int, Int, Int, Int)
}
fn print_color(color : Color) -> Unit {
match color {
Red => println("Red")
Green => println("Green")
Blue => println("Blue")
// Take the three Int values from RGB and print them.
RGB(r, g, b) => println("RGB: \{r}, \{g}, \{b}")
CMYK(c, m, y, k) => println("CMYK: \{c}, \{m}, \{y}, \{k}")
}
}
fn main {
let red = Red
let green = Color::Green
let blue = RGB(0, 0, 255)
let black = CMYK(0, 0, 0, 100)
print_color(red)
print_color(green)
print_color(blue)
print_color(black)
}