thecodex.expert · The Codex Family of Knowledge
Rust

Structs

Like Go, Rust has no classes — a struct groups data, and a separate impl block attaches its behavior.

Rust 1.96 impl blocks Last verified:
Canonical Definition

A struct defines a custom type made of named fields. Behavior is attached separately in one or more impl blocks: a method takes self (or &self, or &mut self) as its first parameter and is called with dot notation; an associated function (no self) is called with ::, and is how constructors like String::new or a custom Point::new are conventionally written.

Defining and instantiating a struct

Field-init shorthand lets you skip repeating field: field when a variable's name matches the field name; struct update syntax (..other) copies remaining fields from an existing instance.

Ruststructs.rs
struct User {
    username: String,
    email: String,
    active: bool,
}

fn build_user(username: String, email: String) -> User {
    User { username, email, active: true }   // field-init shorthand
}

let user1 = build_user(String::from("alice"), String::from("a@x.com"));
let user2 = User { username: String::from("bob"), ..user1 };   // update syntax

Methods and associated functions via impl

&self borrows the instance immutably (most methods); &mut self borrows it mutably (methods that modify); a bare self takes ownership (rare, usually for a conversion that consumes the value).

Rustimpl_block.rs
struct Rectangle { width: f64, height: f64 }

impl Rectangle {
    fn new(width: f64, height: f64) -> Rectangle {   // associated function: Rectangle::new(...)
        Rectangle { width, height }
    }

    fn area(&self) -> f64 {          // method: rect.area()
        self.width * self.height
    }

    fn scale(&mut self, factor: f64) {   // method that mutates
        self.width *= factor;
        self.height *= factor;
    }
}

let mut rect = Rectangle::new(3.0, 4.0);
println!("{}", rect.area());   // 12.0
rect.scale(2.0);
println!("{}", rect.area());   // 48.0

Tuple structs and unit structs

A tuple struct names a tuple type without naming its fields, useful when the position alone is meaningful; a unit struct has no fields at all, commonly used to implement a trait on a type that needs no data.

Rusttuple_structs.rs
struct Point(f64, f64);       // tuple struct
struct AlwaysEqual;            // unit struct — no fields

let origin = Point(0.0, 0.0);
println!("{}", origin.0);      // access by position, like a tuple

Sources

1
The Rust Project. The Rust Programming Language, "Using Structs to Structure Related Data" and "Method Syntax", doc.rust-lang.org/book/ch05.