Skip to content

Struct

Type

Structs define reusable typed data structures.

A struct is a group of unordered typed data fields. Therefore, the data fields can be of any type: a built-in type, another struct type or a protocol.

Rationale

Structs define pure data. In contrast to protocols, they don't express business logic, i.e. events, nor do they carry identity without being embedded in a protocol.

Structs allow reuse: e.g. fields of an Address are used at multiple positions, but must be copies of a group of data fields. Protocols in contrast are always passed around as reference. Protocols can be included in a struct as a field.

Declaration

A struct type is declared by the struct keyword, followed by the type name (starting with Uppercase), and the member field declarations between curly brackets { }. An empty struct, i.e. a struct without fields, may be declared with or without curly braces. If curly braces are omitted, the declaration needs to end with a semicolon ;. A struct parameter, field or variable is declared as any other variable with the user-defined struct type name.

Initialization

A struct is created using either named or positional arguments.

For example, given the structs

struct City {
    zipCode: Text,
    name: Text,
    country: Text
};

struct Address {
    street: Text,
    no: Text,
    city: City
};

initialization might look like

var a = Address(
    street = "Dorfstrasse",
    no = "512",
    city = City("6340", "Baar", "CHE")
);
var b = a.copy(
    no = "513",
    city = a.city.copy(
        country = "Switzerland"
    )
);
var c = a.copy(
    no = "513",
    city = a.city.copy(
        country = "Switzerland"
    )
);

Examples of empty structs:

// semicolon is mandatory here
struct EmptyStructWithoutBraces;

// semicolon is optional for curly braces declaration
struct EmptyStructWithBracesSemiColon { }

struct EmptyStructWithBraces { };

Methods

with(...) reassignment

Deprecated feature (since 2024.1.0, to be removed in 2025.1.0)

copy(...) reassignment

Member fields of a struct variable are immutable.

NPL provides a copy copy-constructor on struct values that copies the struct value with one or more changes to member fields. This works for nested struct types as well. The copy-expression only works with named arguments, each argument is optional.

var a = Address(
    street = "Dorfstrasse",
    no = "512",
    city = City("6340", "Baar", "CHE")
);
var b = a.copy(
    no = "513",
    city = a.city.copy(
        country = "Switzerland"
    )
);
var c = a.copy(
    no = "513",
    city = a.city.copy(
        country = "Switzerland"
    )
);

In the example above, city is resolved lexically inside the body scope of the outer struct a.

Inherited methods

toText

<function> Obtain the Text representation of this.

Receiver

T

Type Arguments

T

Returns

Text - the Text representation of this

Usage

Converts a struct to Text.