Structures
Struct Syntax
Slice supports structures containing one or more named fields of arbitrary type, including user-defined complex types. For example:
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 scope, so the names of the structure fields need to be unique only within their enclosing structure.
Field 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:
struct TwoPoints
{
struct Point // Illegal!
{
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
struct Point
{
short x;
short y;
}
struct TwoPoints // Legal (and cleaner!)
{
Point coord1;
Point coord2;
}
Language Mapping
A Slice structure maps to a Ruby class with the same name. For each Slice field, the Ruby class contains a corresponding instance variable as well as accessors to read and write its value. For example, here is our Employee structure once more:
struct Employee
{
long number;
string firstName;
string lastName;
}
The Ruby mapping generates the following definition for this structure:
class Employee
attr_accessor :number, :firstName, :lastName
def initialize(number=0, firstName='', lastName='')
@number = number
@firstName = firstName
@lastName = lastName
end
def hash
# ...
end
def ==
# ...
end
def inspect
# ...
end
end
The compiler generates a definition for the hash
method, which allows instances to be used as keys in a hash collection. The hash
method returns a hash value for the structure based on the value of its instance variables.
The ==
method returns true if all instance variables of two structures are (recursively) equal.
The inspect
method returns a string representation of the structure.
Generated Constructor
The generated constructor has one parameter for each field. This allows you to construct and initialize an instance in a single statement (instead of first having to construct the instance and then assign to its attributes).
All these parameters have also default values (see Fields).