Skip to content

Structs

A struct groups named fields into one type.

struct Point {
x: int,
y: int,
}

Structs and their fields can carry attributes.

To instantiate a struct, provide all fields by name. To read a field, use dot notation:

let p = Point { x: 10, y: 20 }
let sum = p.x + p.y
30

To write to a field, assign to it. The binding must be mutable:

let mut p = Point { x: 10, y: 20 }
required by p.x = 50
p.x = 50

When a field name matches a binding in scope, the field value can be omitted:

struct User {
name: string,
email: string,
active: bool,
}
fn new_user(name: string, email: string) -> User {
User { name, email, active: true }same as name: name, email: email
}

To copy field values from one instance to another, use .. followed by the source instance. Explicit fields take precedence:

let p1 = Point { x: 10, y: 20 }
let p2 = Point { x: 50, ..p1 }x: 50, y: 20

Use a bare .. to autofill remaining fields with their zero value:

let p = Point { x: 10, .. }x: 10, y: 0
let q = Point { .. }x: 0, y: 0

Each field declares its own write permission. A field whose type has mut is writable. A field without mut is read-only.

struct Index {
counts: mut Map<string, int>,
tags: Slice<string>,
}

In a writable struct, mut fields accept writes:

writable struct
let mut index = Index {
counts: Map.new<string, int>(),writable field
tags: ["draft"],read-only field
}
index.counts["hits"] = 1allowed: index and counts are both mut
index.tags[0] = "final"error: tags has no mut

In a read-only struct, no field accepts writes:

read-only struct
let snapshot = Index {
counts: Map.new<string, int>(),read-only field, because struct is read-only
tags: ["draft"],read-only field
}
snapshot.counts["hits"] = 1error: snapshot is not mut

A tuple struct has positional fields instead of named fields.

struct Color(int, int, int)

To instantiate a tuple struct:

let red = Color(255, 0, 0)

Access fields by position:

let r = red.0255
let g = red.10
let b = red.20

A type parameter lets one struct hold fields of any type. Lisette infers the type from the field values:

struct Pair<T> { first: T, second: T }
let nums = Pair { first: 1, second: 2 }Pair<int>
let names = Pair { first: "alice", second: "bob" }Pair<string>

A struct can embed another struct. The fields and methods of the embedded struct are then available directly on the host struct:

struct Logger {
pub prefix: string,
}
impl Logger {
pub fn log(self) -> string { self.prefix }
}
host struct
struct Server {
embed Logger,embedded struct
pub port: int,
}
let l = Logger { prefix: "[api]" }
let s = Server { Logger: l, port: 8080 }
s.prefixhost reads embedded field
s.log()host calls embedded method