Structs#

This is another option to create your own objects. With struct’s you can define custom data types.

They are useful for small amounts of data, since the whole data is copied to a new location whenever a variable with it gets duplicated. For more complex data structures, use Classes.

Also all members of a struct are visible. So you cannot really encapsulate it. Usually the content of them is managed manually by the users of the struct. Or with the help of methods.

Using a struct#

After that a new variable with the struct as the data type can be declared like this:

Person random_person;

To initialize it with 0’s do this:

random_person = {};

Or call the constructor of the struct which does more initalization:

random_person = Person ();

Defining a struct#

First the struct needs to be defined.

This example shows how a basic struct without much usefulness would look like. (Actually structs are not allowed to have no content. It needs at least one field)

struct Person {
}

As you can see a struct begins with the struct keyword, followed by the name of the data type. By convention this is in “CamelCase”. So the first letter is capitalized and multiple words are linked together.

Fields#

In the curly brackets goes the content of the struct.

struct Person {
    public string name;
    public int age;
}

In structs fields must always be public.

A struct can be also intialized together with the fields:

random_person = { "Hello", 1000 };

The fields are specified in the order they appear in the struct declaration.

Structs can also have static fields. They should be usually private though.

Methods#

A struct can also have methods or that work on it. Also static methods are possible.

struct Person {
    public string name;
    public int age;

    public void print_name () {
        stdout.printf (this.name);
    }
}

They can be then called by the user:

Person random_person = { "Hello", 1000 };

random_person.print_name ();

Custom constructor#

For your own structs you can define one or more constructors that can fill the struct with initial data:

struct Person {
    string name;
    int age;

    public Person () {
        this.name = "Unknown";
    }
}

This constructor writes “Unknown” into the name field of the struct.

Also useful#

  • You can also create aliases of structs: Aliases

  • If you want you can also define constants in structs