OSRust.009: Rust Structs and Methods — Fields, impl, Ownership and Mutable Receivers

A photograph of Rust source code displayed on a laptop screen

Open-Source Rust Programming • Intermediate • Estimated study time: 40 minutes

Infrastructure software often needs to represent equipment, identifiers and counters together. Rust structs combine related values under a named type, while methods attach behavior to that type. Instead of passing unrelated variables between functions, a programmer can express a rack inventory as a single value with clearly defined operations.

Prerequisites and learning objectives

Review Rust scalar and compound types and understand variables, functions and references.

  • Define and instantiate a named-field struct.
  • Distinguish owned fields from borrowed references.
  • Define methods and associated functions with impl.
  • Explain the difference between &self, &mut self and self.
  • Validate state changes and handle numeric overflow without unsafe code.

Named fields and ownership

A struct declaration assigns a type to every field. An instance supplies the values for those fields. For example, Rack contains an owned String label and an unsigned 32-bit server count. Named fields communicate meaning more clearly than a tuple containing two values. Dot notation accesses a field. A mutable binding permits changes to its fields. Moving an owned String into a struct transfers ownership; the original variable cannot be used as though it still owns the string. Review ownership and borrowing for the underlying rules. The Rust Book documents initialization and field shorthand.

Let’s Get Rusty: Structs in Rust. Follow the examples of defining types and attaching behavior. Watch on YouTube.

Methods and associated functions

An impl block defines behavior for a type. A function without a receiver, such as Rack::new, is an associated function. Rust has no mandatory constructor syntax; new is a naming convention. The shorthand Self { label, servers } constructs an instance using parameter names matching field names.

A method accepting &self borrows its instance for reading. A method accepting &mut self requires an exclusive mutable borrow and may update fields. A method accepting self takes ownership of the instance, which is useful for consuming operations. The compiler enforces borrowing rules. A reference returned from a method may remain tied to the instance’s lifetime. See the Rust Book’s methods chapter and the earlier lesson on borrowed string slices.

Structs in Rust: beginner tutorial covering custom data types. Watch on YouTube.

Practice: rack inventory

The program below models a fictional rack. The label method returns a borrowed string slice without cloning the owned String. The add_server method uses checked_add to prevent counter overflow. When the addition exceeds u32::MAX, the question-mark operator returns None before assignment. Successful updates return Some(()). Review Option and Result for early-return behavior.

struct Rack {
    label: String,
    servers: u32,
}

impl Rack {
    fn new(label: String, servers: u32) -> Self {
        Self { label, servers }
    }
    fn label(&self) -> &str {
        &self.label
    }
    fn add_server(&mut self) -> Option<()> {
        self.servers = self.servers.checked_add(1)?;
        Some(())
    }
}

fn main() {
    let mut rack = Rack::new(String::from(“R01”), 12);
    assert_eq!(rack.label(), “R01”);
    assert_eq!(rack.add_server(), Some(()));
    assert_eq!(rack.servers, 13);
    let mut full = Rack::new(String::from(“R02”), u32::MAX);
    assert_eq!(full.add_server(), None);
    assert_eq!(full.servers, u32::MAX);
    println!(“{}: {} servers”, rack.label(), rack.servers);
}

Build and verify

Save the program as rack.rs. Compile with an installed Rust toolchain using the command below, then run ./rack on Linux or macOS:

rustc –edition=2021 -D warnings rack.rs -o rack

Expected output: R01: 13 servers. The assertions check label access, successful increment and rejection of overflow without altering the maximum count. A failed assertion terminates the program. Run the example locally before using related logic in production. A real rack capacity policy must separately enforce physical space, power and cooling limits; the numeric type’s maximum is not an equipment limit.

Exercises and answer key

  • Which method receiver permits field mutation? Answer: &mut self.
  • Why does label return &str instead of String? Answer: borrowing avoids transferring ownership or copying the label.
  • How is the constructor called? Answer: Rack::new(…).
  • What happens when the counter is already u32::MAX? Answer: checked_add returns None; the field remains unchanged.
  • Why avoid treating a numeric overflow check as physical capacity validation? Answer: physical constraints require independent limits.

Featured photograph: Rust code on a laptop, Slashme, Wikimedia Commons, CC0.

We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

Optional 5,000-satoshi contribution QR
Optional 5,000-satoshi contribution. Independently confirm the wallet address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and payment amount before sending.

BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

Leave a Reply