Skip to content

Structs

This section describes how to use named structures to store multiple types in one variable.

A Struct is a custom structure container of other types. You can use it so that one variable can store a bunch of other member variables inside it. Member variables can be any type, including other custom structs.

A struct signature is: struct struct_name { … }. Inside the ”…” are normal variable declarations. Then to instantiate a variable of the custom type you just use: struct_name variable_name;

Note, structures must be defined at the namespace scope, i.e. outside of other braces { } that are not used for namespacing.

The following example creates a custom struct type with different member types.

// blueprint
struct weapon {
i32 price;
f32 power;
string name;
}
// construction
weapon sword;

Struct members are accessed by placing a period between the structure variable name and the member variable name: variable_name.member_name

All structure members are zero initialized when constructed.

println(sword.price); // 0
sword.price = 200;
println(sword.price); // 200

Member values can be individually set like the example above or all at once using an initializer list [ ] expression.

weapon sword = [ 200, 5.5, "Great Sword" ];
println(sword.price); // 200
println(sword.power); // 5.500000
println(sword.name); // Great Sword

Struct variables can be cloned (deep copy) using assignment.

weapon sword2 = sword;
println(sword2.price); // 200
println(sword2.power); // 5.500000
println(sword2.name); // Great Sword

You can build structures from other structures using composition or membership. Membership uses a member variable with a struct type. Composition uses a struct type without giving it a member name.

Both strategies are useful for building structures. Membership is more hierarchical and can make large structures more organized. Whereas composition is more flat, requires less typing, and can be slightly faster to execute.

// other structure we want to use
struct position {
f32 x, y;
}
// adding x,y variables using membership
struct player {
position pos; // has variable name
}
player p;
p.pos.x = 1.0; // x and y added using a position member variable
p.pos.y = 2.0;
println("{p.pos.x}, {p.pos.y}"); // 1.00000, 2.00000
p.pos = [ 3.0, 4.0 ]; // update using initializer list
println("{p.pos.x}, {p.pos.y}"); // 3.00000, 4.00000
// adding x,y variables using composition
struct beast {
position; // no variable name
}
beast b;
b.x = 1.0; // x and y added directly to the beast structure
b.y = 2.0;
println("{b.x}, {b.y}"); // 1.00000, 2.00000
b = [ 3.0, 4.0 ]; // update using initializer list
println("{b.x}, {b.y}"); // 3.00000, 4.00000