Structs
A struct is defined using the struct keyword.
struct_def = "struct" IDENT "{" [ struct_fields ] "}" ;
struct_fields = struct_field { "," struct_field } [ "," ] ;
struct_field = IDENT ":" type ;
Struct Definition
Field names MUST be unique within a struct.
struct Point {
x: i32,
y: i32,
}
A struct definition MAY be prefixed with the linear keyword, making it a linear (must-consume) type: a value of a linear struct type must be explicitly consumed and cannot be implicitly dropped. The linear modifier and its full semantics — including infectious linearity through fields and arrays — are specified with move semantics (3.8), not repeated here.
Struct Instantiation
All fields MUST be initialized when creating a struct instance.
Field initializers MAY be provided in any order.
struct Point { x: i32, y: i32 }
fn main() -> i32 {
// Fields can be initialized in any order
let p = Point { y: 20, x: 10 };
p.x + p.y
}
Struct Usage
Struct fields are accessed using dot notation.
A field of a mutable struct binding is a place and may be the target of an assignment (5.2:1, 5.2:2); assigning to it drops the field's prior value, if live, before storing the new one (overwrite-drop, 5.2:1). Assigning to a field of an immutable binding is a compile-time error (5.2:8).
struct Counter { value: i32 }
fn main() -> i32 {
let mut c = Counter { value: 0 };
c.value = c.value + 1;
c.value
}