Structs
Declaration
Section titled “Declaration”A struct groups named fields into one type.
struct Point { x: int, y: int,}Structs and their fields can carry attributes.
Instantiation
Section titled “Instantiation”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.y30To write to a field, assign to it. The binding must be mutable:
let mut p = Point { x: 10, y: 20 }required by p.x = 50p.x = 50When 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: 20Use a bare .. to autofill remaining fields with their zero value:
let p = Point { x: 10, .. }x: 10, y: 0let q = Point { .. }x: 0, y: 0Write permission in fields
Section titled “Write permission in fields”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 structlet mut index = Index { counts: Map.new<string, int>(),writable field tags: ["draft"],read-only field}
index.counts["hits"] = 1allowed: index and counts are both mutindex.tags[0] = "final"error: tags has no mutIn a read-only struct, no field accepts writes:
read-only structlet 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 mutTuple structs
Section titled “Tuple structs”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.0255let g = red.10let b = red.20Generic structs
Section titled “Generic structs”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>Embedding
Section titled “Embedding”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 structstruct Server { embed Logger,embedded struct pub port: int,}
let l = Logger { prefix: "[api]" }let s = Server { Logger: l, port: 8080 }
s.prefixhost reads embedded fields.log()host calls embedded method