Skip to main content
Skip table of contents

Structures

Struct Syntax

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

SLICE
module M
{
    struct TimeOfDay
    {
        short hour;         // 0 - 23
        short minute;       // 0 - 59
        short second;       // 0 - 59
    }
}

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:

SLICE
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
SLICE
struct Point
{ 
    short x;
    short y;
}

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

Language Mapping

A Slice structure maps to a PHP class containing a public variable for each field of the structure. For example, here is our Employee structure once more:

SLICE
struct Employee
{
    long number;
    string firstName;
    string lastName;
}

The PHP mapping generates the following definition for this structure:

PHP
class Employee
{
    public $number;
    public $firstName;
    public $lastName;

    public function __construct($number=0, $firstName='', $lastName='');
    public function __toString();
}

The mapping includes a definition for the __toString magic method, which 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 variables).

All these parameters have also default values (see Fields).

See Also
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.