SyntaxStudy
Sign Up
Rust Defining and Instantiating Structs
Rust Beginner 1 min read

Defining and Instantiating Structs

Structs are the primary way to group related data in Rust. A struct definition names a set of fields, each with a type. You instantiate a struct with field initializers in any order and access fields with dot notation. If a variable has the same name as a field, the field init shorthand lets you write `name` instead of `name: name`. Rust has three kinds of structs: named-field structs (the most common), tuple structs (which have unnamed positional fields and are useful for newtype wrappers), and unit-like structs (which have no fields at all and are often used as marker types for trait implementations). All three can implement traits and have methods defined on them. To print a struct's debug representation you derive the `Debug` trait with `#[derive(Debug)]`. Then you can use the `{:?}` (compact) or `{:#?}` (pretty-printed) format specifiers. Deriving `Clone` gives you a `.clone()` method; deriving `PartialEq` enables `==` comparisons; deriving `Default` provides default field values. These derives eliminate boilerplate while keeping behaviour explicit.
Example
#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}

// Tuple struct — a newtype wrapper
#[derive(Debug, Clone, Copy)]
struct Meters(f64);

// Unit-like struct
#[derive(Debug)]
struct Marker;

fn main() {
    // Named-field struct
    let origin = Point { x: 0.0, y: 0.0 };
    println!("origin = {:?}", origin);

    // Field init shorthand
    let x = 3.0_f64;
    let y = 4.0_f64;
    let p = Point { x, y };
    println!("p = {:#?}", p);

    // Struct update syntax — copy remaining fields from another instance
    let q = Point { x: 1.0, ..p };
    println!("q = {:?}", q);

    // PartialEq derived
    println!("p == q : {}", p == q);
    println!("p == p.clone() : {}", p == p.clone());

    // Tuple struct
    let dist = Meters(42.5);
    println!("distance = {} m", dist.0);

    // Unit-like struct
    let _m = Marker;
    println!("marker = {:?}", _m);

    // Destructuring
    let Point { x: px, y: py } = p;
    println!("destructured: px={px}  py={py}");
}