Struct (Rust)
A struct is a custom data type that groups related named fields into one value. Structs are how you model real-world entities in Rust, similar to objects or records in other languages.
Rust
Rust has three flavors: classic structs with named fields, tuple structs (fields by position), and unit structs (no fields, used as markers). You create an instance with the struct name and field values, then access fields with dot notation.
Structs hold only data. Behavior lives in separate impl blocks, where you define methods (functions whose first parameter is self, &self, or &mut self) and associated functions (like constructors, conventionally named new).
Common derives — #[derive(Debug, Clone, PartialEq)] — auto-generate printing, copying, and equality so you don't write boilerplate. Structs pair naturally with enums and traits to model your domain.
Syntax
struct User { name: String, age: u32 }
let u = User { name: String::from("Ana"), age: 30 };Examples
Rust
#[derive(Debug)]
struct Point { x: i32, y: i32 }
impl Point {
fn new(x: i32, y: i32) -> Self { Point { x, y } }
}
fn main() {
let p = Point::new(1, 2);
println!("{:?}", p);
}Output:
Point { x: 1, y: 2 }