LEARN VOID / DATA & BEHAVIOR

Initialization

Give data a valid starting state.

Complete program for the synchronous entry adapter. The result below is the returned integer.

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

func (item label) init(text: string = "Ready"):
    item.text = text

struct package:
    title: label
    item_count: i32 = 1

func entry(extra_items: i32) -> i32:
    var parcel = package()
    parcel.item_count += extra_items
    return parcel.item_count
Input 5Expected result 6

Prepare fields before use

A label declares a default text, then its initializer replaces it with the provided text or the default argument "Ready". The package’s nested value label is initialized before the package is used; parcel.title.text is therefore "Ready".

Construct directly with the type name

package() prepares its nested label and sets item_count to 1. Adding input 5 gives 6. There is no new keyword. With a custom initializer, constructor arguments bind to its parameters; they do not also override arbitrary fields.

Preserve construction rules

Required value children must be constructible before a value initializer body starts. Required nonnullable managed fields follow explicit initialization rules, rather than implicitly allocating children. Assignments and ordinary copies do not rerun init. Readonly bindings become readonly after successful construction; direct .init() calls are not allowed.