Structs
Declaration
Section titled “Declaration”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.
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 a field, assign to it through a mutable binding:
let mut p = Point { x: 10, y: 20 }p.x = 50When a field name matches a binding in scope, the field value can be omitted:
let x = 10let y = 20let p = Point { x, y }x: 10, y: 20To 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.
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 fieldfirst.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 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”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>Embedding
Section titled “Embedding”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 fieldlet _ = s.log()host calls embedded method