Structs
Structs are value types that group related data together. They have deterministic layout and copy semantics.
Defining Structs
nic
struct Point {
x: f64,
y: f64
}
struct Person {
name: string,
age: i32
}Fields are separated by commas. The last comma is optional.
Creating Struct Instances
Use struct literals with field names:
nic
fn main() -> unit {
let p: Point = Point{x: 3.0, y: 4.0};
let person: Person = Person{name: "Alice", age: 30};
return;
}Accessing Fields
Use dot notation to read and write fields:
nic
fn main() -> unit {
let p: Point = Point{x: 3.0, y: 4.0};
// Read fields
let x_val: f64 = p.x;
let y_val: f64 = p.y;
// Write fields (structs are mutable)
let q: Point = Point{x: 0.0, y: 0.0};
q.x = 10.0;
q.y = 20.0;
return;
}Structs as Parameters
nic
struct Rectangle {
width: f64,
height: f64
}
fn area(rect: Rectangle) -> f64 {
return rect.width * rect.height;
}
fn main() -> unit {
let r: Rectangle = Rectangle{width: 10.0, height: 5.0};
let a: f64 = area(r); // 50.0
return;
}Visibility
Fields are private by default. Use pub to make them accessible from outside the module:
nic
struct Config {
pub name: string, // public
pub timeout: i32, // public
internal_id: i32 // private
}The struct itself can also be marked pub:
nic
pub struct PublicStruct {
pub field: i32
}Generic Structs
Structs can have type parameters:
nic
struct Pair[T, U] {
first: T,
second: U
}
fn main() -> unit {
let p: Pair[i32, string] = Pair{first: 42, second: "answer"};
return;
}Nested Structs
Structs can contain other structs:
nic
struct Point {
x: f64,
y: f64
}
struct Line {
start: Point,
end: Point
}
fn main() -> unit {
let line: Line = Line{
start: Point{x: 0.0, y: 0.0},
end: Point{x: 10.0, y: 10.0}
};
let start_x: f64 = line.start.x;
return;
}Pointers to Structs
When working with struct pointers, field access auto-dereferences:
nic
fn main() -> unit {
let p: Point = Point{x: 1.0, y: 2.0};
let ptr: *Point = &p;
// Auto-dereference: ptr.x instead of (*ptr).x
let x: f64 = ptr.x;
ptr.y = 5.0;
return;
}Heap-Allocated Structs
Use new to allocate on the heap:
nic
fn main() -> unit {
let p: *Point = new Point { x: 1.0, y: 2.0 };
p.x = 10.0; // auto-deref
release p; // must free heap memory
return;
}Summary
| Feature | Syntax |
|---|---|
| Definition | struct Name { field: Type, ... } |
| Instance | Name{field: value, ...} |
| Field access | instance.field |
| Generic | struct Name[T] { field: T } |
| Public | pub struct Name { pub field: Type } |
Next
Learn about Enums for algebraic data types.