Skip to content

Struct Fields

Struct fields are typed values stored on each instance.

struct User {
name: string
age: int
}
let user = User()
user.name = "Martin"
user.age = 19

Use dot access to read fields.

println(user.name)
println(user.age)

Assign fields with =.

user.name = "Nubo"

Field assignments are type-checked.

struct User {
age: int
}
let user = User()
user.age = 19

This is valid because age expects an int.

This is invalid:

// Runtime/type error:
user.age = "nineteen"

Struct instances are locked after creation. You cannot freely add random fields unless they were declared or implemented through impl.

struct User {
name: string
}
let user = User()
// Error:
user.email = "[email protected]"

Declare the field if it should exist:

struct User {
name: string
email: string
}

Struct instances can be iterated as key/value pairs over declared fields.

struct User {
name: string
age: int
}
let user = User()
user.name = "Martin"
user.age = 19
for key, value in user {
println(key, value)
}

The key is the field name. The value is the field value.

Structs have an internal $convout hook that converts public fields into a dictionary-like output.

Private fields are skipped.

struct User {
name: string
private password: string
}

Only name is included in public conversion output.