Skip to content

Structs & impl

Structs & impl

Defining a struct

Structs are nominal record types with named fields:

struct Point:
x: i32
y: i32

Using structs as parameters

Structs are passed as function parameters by value:

struct Point:
x: i32
y: i32
func sum(point: Point) -> i32:
return point.x + point.y

There is no struct constructor literal syntax today. Structs are passed through function parameters, returned from extern calls, or created via runtime-backed APIs.

Field access

Use . notation to read struct fields:

struct Rect:
width: i32
height: i32
func area(rect: Rect) -> i32:
return rect.width * rect.height

Nested structs

struct Point:
x: i32
y: i32
struct Rect:
origin: Point
width: i32
height: i32
func perimeter_seed(rect: Rect) -> i32:
return rect.origin.x + rect.origin.y + rect.width + rect.height

Impl blocks

Methods live in an impl block named after the target struct. Methods use an explicit self parameter:

struct Counter:
value: i32
impl Counter:
func current(self) -> i32:
return self.value
func bump(self) -> i32:
return self.value + 1

Methods are called via dot notation: counter.current().

Generic struct surface

The parser accepts generic struct syntax, but generic structs and generic impl blocks are not yet fully available end to end:

struct Pair<T>:
left: T
right: T

For production code use non-generic structs.

Operator overloading

Operator overloading via __add__, __mul__, etc. is not implemented in the current compiler.