Structures

Slice supports structures containing one or more named members of arbitrary type, including user-defined complex types. For example:

Slice 支持包含一个或多个任意类型的命名成员的结构,包括用户定义的复杂类型。 例如:

1
2
3
4
5
6
7
8
9
module M
{
struct TimeOfDay
{
short hour; // 0 - 23
short minute; // 0 - 59
short second; // 0 - 59
}
}

As in C++, this definition introduces a new type called TimeOfDay. Structure definitions form a namespace, so the names of the structure members need to be unique only within their enclosing structure.

Data member definitions using a named type are the only construct that can appear inside a structure. It is impossible to, for example, define a structure inside a structure:

与 C++ 中一样,此定义引入了一种称为 TimeOfDay 的新类型。 结构定义形成命名空间,因此结构成员的名称仅在其封闭结构内必须是唯一的。

使用确定类型的数据成员定义是唯一可以出现在结构内部的构造。 例如,不可能在结构内定义结构:

1
2
3
4
5
6
7
8
9
10
struct TwoPoints 
{
struct Point // 非法!
{
short x;
short y;
}
Point coord1;
Point coord2;
}

This rule applies to Slice in general: type definitions cannot be nested (except for modules, which do support nesting). The reason for this rule is that nested type definitions can be difficult to implement for some target languages and, even if implementable, greatly complicate the scope resolution rules. For a specification language, such as Slice, nested type definitions are unnecessary – you can always write the above definitions as follows (which is stylistically cleaner as well):

此规则一般适用于 Slice:类型定义不能嵌套(模块除外,模块支持嵌套)。 此规则的原因是嵌套类型定义对于某些目标语言可能难以实现,并且即使可以实现,也会使范围解析规则变得非常复杂。 对于规范语言,例如 Slice,嵌套类型定义是不必要的 - 您始终可以按如下方式编写上述定义(这在风格上也更清晰):

1
2
3
4
5
6
7
8
9
10
11
struct Point
{
short x;
short y;
}

struct TwoPoints // Legal (and cleaner!)
{
Point coord1;
Point coord2;
}

You can specify a default value for a data member that has one of the following types:

您可以为具有以下类型之一的数据成员指定默认值:

  1. An integral type (byte, short, int, long)
  2. A floating point type (float or double)
  3. string
  4. bool
  5. enum

For example:

1
2
3
4
5
6
7
struct Location
{
string name;
Point pt;
bool display = true;
string source = "GPS";
}

The legal syntax for literal values is the same as for Slice constants, and you may also use a constant as a default value. The language mapping guarantees that data members are initialized to their declared default values using a language-specific mechanism.

字符值的合法语法与 Slice 常量相同,您也可以使用常量作为默认值。 语言映射保证使用特定于语言的机制将数据成员初始化为其声明的默认值。