LEARN VOID / DATA & BEHAVIOR

Initialization

Give data a valid starting state.

initialization.voidDownload source ↓
value struct label:
    text: string = "before"

func (l label) init(text: string = "ready"):
    l.text = text

struct message:
    title: string
    nested: label

func (m message) init(text: string = "done"):
    m.title = m.nested.text + text

func entry(value: i32) -> i32:
    var m = message()
    const item = label()
    var copy = item
    copy.text += "!"
    if m.title == "readydone" and copy.text == "ready!" and item.text == "ready":
        return value + 2
    return -100
Input 5Expected result 7

Start from declared defaults

Fields can declare defaults, and supported defaultable fields receive safe initial values. Custom init methods run within the language’s construction rules; required value fields must already be complete before a value initializer begins.

Add focused initialization logic

label starts with before, then its init replaces that text with ready. The managed message initializer can use its already-initialized nested label, producing readydone.

Construct without ceremony

Construct with the type name; there is no new keyword. Default and named arguments follow the supported initializer signature. This example also shows that copying a readonly value into an independent mutable value does not make every later copy readonly.