Constructors and Init
Automatic initialization
Section titled “Automatic initialization”When a user struct has no explicit init, its public fields become constructor arguments in declaration order. Named arguments make the call easier to read:
struct Point { x: int private token: string y: int}
let named = Point(x: 5, y: 8)let positional = Point(5, 8)let mixed = Point(5, y: 8)let defaults = Point(y: 8)
println(named.x)println(defaults.x)Private fields are not constructor parameters. Omitted fields retain their type defaults, such as 0, "", nil for nullable fields, and empty typed collections. Each instance receives its own default collections.
The automatic initializer checks types and rejects private or unknown fields, duplicate assignments, and excess arguments. Argument expressions run once in source order. Positional arguments are allowed, but named arguments are preferred when fields have similar types.
Explicit initialization
Section titled “Explicit initialization”Define init inside impl when you need custom defaults, validation, or setup. An explicit initializer replaces automatic field initialization as the constructor’s argument API.
struct User { name: string age: int}
impl User { fn init(self: User, name: string = "Guest", age: int = 0) void { if age < 0 { panic("age cannot be negative") }
self.name = name self.age = age }}
let guest = User()let user = User(age: 19, name: "Martin")let positional = User("Ada", 30)
println(guest.name)println(user.age)init is a function, so named arguments and defaults work just as they do for ordinary function calls. self is the pre-created instance and is bound automatically; callers do not pass it.
Return void for ordinary setup
Section titled “Return void for ordinary setup”Use void when initializing the provided self. You do not need to return the instance just to make construction work.
An initializer may instead return its struct type when it needs to supply a replacement instance, such as a cached singleton:
struct Config { name: string}
let shared: Config? = nil
impl Config { fn init(self: Config) Config { if !isNil(shared) { return shared }
self.name = "Nubo" shared = self
return self }}
let first = Config()let second = Config()first.name = "Changed"
println(second.name)See Singletons for more examples.
Factory functions
Section titled “Factory functions”Use a normal function when construction needs application-specific logic:
struct User { name: string}
fn createGuest() User { return User(name: "Guest")}
let guest = createGuest()println(guest.name)This factory uses the automatic initializer because this independent example defines no explicit init.