在 Ballerina 中创建和使用枚举的惯用方法是什么?
What is the idiomatic way to create and use Enumerations in Ballerina?
Found some evidence here that enum was supported in Ballerina at one point, but it seems to have been removed。有人知道在 Ballerina 中处理枚举值的 recommended/supported/idiomatic 方法吗?
是的,我们刚才从语言中删除了枚举类型。现在您可以使用常量和联合类型一般地定义枚举值。
// Following declarations declare a set of compile-time constants.
// I used the int value for this example. You could even do const SUN = "sun".
const SUN = 0;
const MON = 1;
const TUE = 2;
const WED = 3;
const THU = 4;
const FRI = 5;
const SAT = 6;
// This defines a new type called "Weekday"
type Weekday SUN | MON | TUE | WED | THU | FRI | SAT;
function play() {
Weekday wd1 = WED;
Weekday wd2 = 6;
// This is a compile-time error, since the possible values
// which are compatible with the type "Weekday" type are 0, 1, 2, 3, 4, 5, and 6
Weekday wd3 = 8;
}
让我根据语言规范解释一下这是如何工作的。考虑以下类型定义。您可以将可能的整数值和布尔值(true
或 false
)分配给类型为 IntOrBoolean
.
的变量
type IntOrBoolean int | boolean;
IntOrBoolean v1 = 1;
IntOrBoolean v2 = false;
同样,您可以定义一个新的类型定义,它只包含像这样的几个值。这里 0
表示一个单例类型,其值为 0
,1
表示另一个单例类型,其值为 1
。单例类型是一种在其值集中只有一个值的类型。
type ZeroOrOne 0 | 1;
有了这个理解,我们可以重写我们的 Weekday
类型如下。
type Weekday 0 | 1 | 2 | 3 | 4 | 5| 6;
当你定义一个compile-time常量如const SUN = 0
时,变量SUN
的类型不是int
,而是一个单例类型,值为0
。
Found some evidence here that enum was supported in Ballerina at one point, but it seems to have been removed。有人知道在 Ballerina 中处理枚举值的 recommended/supported/idiomatic 方法吗?
是的,我们刚才从语言中删除了枚举类型。现在您可以使用常量和联合类型一般地定义枚举值。
// Following declarations declare a set of compile-time constants.
// I used the int value for this example. You could even do const SUN = "sun".
const SUN = 0;
const MON = 1;
const TUE = 2;
const WED = 3;
const THU = 4;
const FRI = 5;
const SAT = 6;
// This defines a new type called "Weekday"
type Weekday SUN | MON | TUE | WED | THU | FRI | SAT;
function play() {
Weekday wd1 = WED;
Weekday wd2 = 6;
// This is a compile-time error, since the possible values
// which are compatible with the type "Weekday" type are 0, 1, 2, 3, 4, 5, and 6
Weekday wd3 = 8;
}
让我根据语言规范解释一下这是如何工作的。考虑以下类型定义。您可以将可能的整数值和布尔值(true
或 false
)分配给类型为 IntOrBoolean
.
type IntOrBoolean int | boolean;
IntOrBoolean v1 = 1;
IntOrBoolean v2 = false;
同样,您可以定义一个新的类型定义,它只包含像这样的几个值。这里 0
表示一个单例类型,其值为 0
,1
表示另一个单例类型,其值为 1
。单例类型是一种在其值集中只有一个值的类型。
type ZeroOrOne 0 | 1;
有了这个理解,我们可以重写我们的 Weekday
类型如下。
type Weekday 0 | 1 | 2 | 3 | 4 | 5| 6;
当你定义一个compile-time常量如const SUN = 0
时,变量SUN
的类型不是int
,而是一个单例类型,值为0
。