Structs
Structs
Section titled “Structs”struct declares a nominal type:
Int x, y; is shorthand for two fields of the same type.
Layout Options
Section titled “Layout Options”Struct layout options are written after struct:
packed places fields without natural field padding. align = N sets the aggregate alignment to at
least N, and N must be a power of two. Option order does not matter, so
struct [align = 8, packed] is equivalent to struct [packed, align = 8]. Repeating the same option is
an error.
Default Constructors
Section titled “Default Constructors”Structs without custom init can use the compiler-provided default constructor. The default
constructor uses field names as required argument labels:
Positional arguments are not accepted for the default constructor:
Fields can have default values. A field with a default value can be omitted from the default constructor call:
When an expected type is available, the type name can be omitted with .(...):
Owning pointers can auto-dereference when the expected type is the pointee type. Field access can
also pass through T^:
Field Mutability
Section titled “Field Mutability”A field is writable only when both the access path and the field declaration are writable. An
immutable binding, a shared T&, or another access path without write capability freezes reachable
fields:
init is a constructor entry in a struct body:
Use init(self, ...) for ordinary custom constructors. self names the initializing target and is
not supplied at the call site. Remaining parameters follow normal function argument rules, including
named arguments and defaults. Once a struct declares any custom init, the compiler-provided field
constructor is not used.
A named initializer is declared with init name(self, ...) and called through the same value or heap
construction syntax:
Named and unnamed initializers form separate overload families. A named initializer is a constructor entry, not a normal function value.
deinit
Section titled “deinit”deinit is declared without a return type:
Methods
Section titled “Methods”Types define an instance method by putting a receiver first in the parameter list. Functions without a receiver are associated functions:
The receiver shorthand self is readonly Self&. A method that writes mutable fields declares
Self&! self explicitly; borrow checking creates a unique mutable reborrow at the call site.
Local Declarations
Section titled “Local Declarations”Local variable declarations bind one name at a time: