DerefMut in Rust

The DerefMut trait in Rust is a powerful feature that allows for mutable access to the inner type of a smart pointer. It extends the capabilities of the Deref trait, enabling developers to modify the data within a smart pointer. This trait is essential for creating flexible and reusable abstractions in Rust, particularly when dealing with types defined outside of one's own crate.

Overview

The DerefMut trait serves as the mutable counterpart to the Deref trait. It allows for mutable dereferencing of a type, enabling the use of methods from the dereferenced type. This trait is particularly useful when you need to coerce one type into another, allowing for more flexible and powerful manipulation of data structures. The primary function of DerefMut is to provide a mutable reference to the target type, enabling modification of the data within the smart pointer.

Definition and Implementation

Implementing DerefMut is straightforward once Deref is in place. The process involves creating a deref_mut method that returns a mutable reference to the target type. The function signature for DerefMut is similar to that of Deref, but it specifically uses mutable references. The DerefMut trait is defined as follows:

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}

This trait allows custom types to access and modify the methods of the types they encapsulate. To implement DerefMut, you can often copy the Deref implementation, remove the line with the associated type, and add mut where necessary.

Example: Implementing Deref and DerefMut

Consider the following example where both Deref and DerefMut are implemented for a custom type HoldsANumber:

use std::ops::{Deref, DerefMut};

struct HoldsANumber(u8);

impl HoldsANumber {
    fn prints_the_number_times_two(&self) {
        println!("{}", self.0 * 2);
    }
}

impl Deref for HoldsANumber {
    type Target = u8;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for HoldsANumber {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

fn main() {
    let mut my_number = HoldsANumber(20);
    *my_number = 30;                               // DerefMut lets us do this.
    println!("{:?}", my_number.checked_sub(100));
    my_number.prints_the_number_times_two();
}

In this example, HoldsANumber is a struct that holds a u8 value. By implementing Deref, we allow HoldsANumber to access all methods available to u8. The DerefMut implementation further extends this capability by allowing mutable access, enabling us to modify the value inside HoldsANumber.

Use Cases

The DerefMut trait is particularly useful in scenarios where you need to:

  • Extend the functionality of types from external crates without modifying their source code.
  • Provide a consistent interface for mutable access to the inner data of complex types.
  • Implement custom smart pointers or other abstractions that require mutable dereferencing.

By leveraging the DerefMut trait, Rust developers can create flexible and reusable abstractions that integrate seamlessly with the language's ownership and borrowing system.

Example: Deref and DerefMut for Vec

The Rust standard library provides implementations of Deref and DerefMut for the Vec type. Below is a snippet of how these traits are implemented for Vec:

impl<T, A: Allocator> ops::Deref for Vec<T, A> {
   type Target = [T];

   fn deref(&self) -> &[T] {
       unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
   }
}

impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
   fn deref_mut(&mut self) -> &mut [T] {
       unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
   }
}

In this implementation, dereferencing a Vec will coerce it into a slice using its raw pointer and length. This operation is temporary, meaning that the slice cannot be resized, and its length is fixed at the time of dereferencing. The use of unsafe code here is necessary to perform the raw pointer manipulation required for this conversion.

Conclusion

The DerefMut trait is a powerful feature in Rust that allows for mutable dereferencing, enabling more flexible manipulation of types. By implementing DerefMut, types like Vec can be seamlessly coerced into slices, providing a more intuitive and efficient way to work with collections in Rust. Understanding and implementing DerefMut allows developers to create custom types that not only access but also modify the methods and properties of the types they encapsulate.

| Book Title | Usage of derefmut | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Discusses `DerefMut` as a tool for mutable access to the inner type of a smart pointer. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/1) | Explains the requirement of implementing `Deref` before `DerefMut`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/69) | Connects `DerefMut` to `Deref` and smart pointers. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/69) | Provides an example with a custom type `HoldsANumber`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/1) | Shows how to modify data within a smart pointer. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/69) |
| [Idiomatic Rust](https://www.manning.com/books/idiomatic-rust) | Highlights `DerefMut` for working around limitations with external types. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-7/155) | Discusses using `DerefMut` for wrapper structs. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-7/155) | Links `DerefMut` to extending functionality of external types. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-7/155) | Example with a generic wrapper struct `MyWrapper`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-7/155) | Useful for extending types from external crates. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-7/155) |
| [Code Like a Pro in Rust](https://www.manning.com/books/code-like-a-pro-in-rust) | Describes `DerefMut` for mutable dereferencing and type coercion. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/68) | Explains coercion of types like `Vec` into slices. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/68) | Connects `DerefMut` to type coercion and method access. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/68) | Example with `Vec` type and its conversion to slices. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/73) | Demonstrates efficient manipulation of collections. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-4/68) |

FAQ (Frequently asked questions)

What is required before implementing DerefMut?

How is the function signature for DerefMut different from Deref?

How can DerefMut help with implementing traits for external types?