Structs
Spice offers support for C-like structs to aggregate variables in groups.
Usage¶
To declare a struct, list all field types with names like this:
Structs can only be declared in the global scope, like functions and procedures.
For creating an instance of the declared struct, you can pass values for either all or none of the fields in curly braces. To access a field of the instance, you can address the field by its name:
| Spice | |
|---|---|
Default field values¶
Fields can be given default values. A field with a default value does not need to be supplied when instantiating the struct without a constructor:
| Spice | |
|---|---|
Public and private fields¶
All fields are private by default — they are only accessible within the same source file. Mark individual fields
public to expose them to code that imports the struct:
| Spice | |
|---|---|
This follows the same visibility rules as functions and structs themselves.
Struct composition¶
The compose qualifier lets you embed one struct inside another
and access its fields directly on the outer struct, without going through an intermediate field name:
| Spice | |
|---|---|
Multiple structs can be composed; if two composed structs expose the same field name, the compiler will require an explicit qualifier to disambiguate.
Adding behavior¶
Structs can be extended with methods, constructors and destructors, and can implement interfaces.