Skip to content

Structs

A struct groups named fields into one type.

struct Point {
x: int,field x, type int
y: int,field y, type 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.y30

To write a field, assign to it through a mutable binding:

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

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

let x = 10
let y = 20
let p = Point { x, y }x: 10, y: 20

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.

struct Index {
counts: mut Map<string, int>,writable, through a writable Index
tags: Slice<string>,read-only
}

A field is writable only through a writable struct.

let mut first = Index {
counts: Map.new<string, int>(),
tags: ["lisette"],
}
first.counts["hits"] = 1writable struct, writable field
first.tags[0] = "go"error: first.tags is read-only
let second = Index {
counts: Map.new<string, int>(),
tags: ["lisette"],
}
second.counts["hits"] = 1error: second was declared without 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

Structs accept type parameters:

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

A struct can embed another struct. This composes the embedded struct’s methods and fields into the host struct:

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