Sling Academy
Home/Rust/Managing Mutability in Rust Struct Methods: &self vs &mut self

Managing Mutability in Rust Struct Methods: &self vs &mut self

Last updated: January 03, 2025

When programming, particularly in systems languages like Rust, understanding how to manage mutability is a fundamental skill. Rust's ownership model incorporates mutability rules to ensure thread safety and memory safety, making it crucial for developers to master the nuances of mutable and immutable references. In this article, we will dive into how to manage mutability in Rust struct methods using &self and &mut self, exploring appropriate use cases and benefits.

Understanding &self vs &mut self

In Rust, methods are defined within an impl block for a struct and can take three primary forms of the self parameter: self, &self, and &mut self. Let's explore the difference between &self and &mut self.

&self: Immutable Borrow

The &self parameter signifies an immutable borrow of the instance. This means within the body of the method, fields cannot be modified. This form is appropriate when you want your method to only read data from the instance, without making any changes.

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    // Method to calculate the distance from origin
    fn distance_from_origin(&self) -> f64 {
        ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
    }
}

In this example, distance_from_origin takes &self, meaning you can call this method as many times as you want without any changes to the Point struct's state. It guarantees other parts of your code can call this method without fear of alteration.

&mut self: Mutable Borrow

The &mut self parameter, on the other hand, is used when you need to modify the instance’s state. You must ensure that the struct is mutable when calling this method.

impl Point {
    // Method to set new coordinates
    fn move_to(&mut self, new_x: i32, new_y: i32) {
        self.x = new_x;
        self.y = new_y;
    }
}

This move_to method allows alteration of a Point's state, changing its x and y coordinates. Since it takes a mutable borrow, only one such borrow can exist at any time, ensuring exclusive access for writing purposes, thus preventing races or unexpected behaviors.

Choosing the Right Approach

Choosing between these borrowing strategies is critically established by your use case:

  • Use &self when the method purely queries or computes based on the instance without requiring changes.
  • Use &mut self when changes need to be made to the instance. Ensure that no others may hold an immutable reference when using this.

Practical Example: Building a Counter

Let’s consider a simple struct for a counter that needs both immutability and mutability to function effectively.

struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }

    // Get current counter value
    fn get_count(&self) -> u32 {
        self.count
    }

    // Increment the count
    fn increment(&mut self) {
        self.count += 1;
    }
}

fn main() {
    let mut counter = Counter::new();

    println!("Current count: {}", counter.get_count());
    counter.increment();
    println!("Updated count: {}", counter.get_count());
}

In this counter example, the get_count method uses &self because it only needs to read and return a field, maintaining clear immutability guarantees. Conversely, the increment needs altering capability, thereby it uses &mut self. Using &mut self ensures changes happen safely, exemplifying one of Rust’s core principles of enforcing safe code by design.

Conclusion

Managing mutability in Rust proceeds from Rust’s hardcore principle of safety without a garbage collector. A robust understanding of &self and &mut self firmly elevates your ability to write efficient, error-free code rooted in immutability pledges unless needed explicitly otherwise. Mastering these concepts will steer your understanding towards the language's higher-order agenda for safety and concurrency without sacralizing performance.

Next Article: Inheriting Behavior Through Composition of Rust Structs

Previous Article: Refactoring Code with Inline Struct Declarations in Rust

Series: Working with structs in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior