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,
}

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.

Mutable struct values allow field reassignment.

struct Counter { value: i32 }

fn main() -> i32 {
    let mut c = Counter { value: 0 };
    c.value = c.value + 1;
    c.value
}