Rust Deref

Deref is a #202204061235 that allows the dereferencing of a #data-structure or an enum. It is especially useful in #202111301656. All structures that implement the trait Deref must have the method deref implemented into them. This is shown as follow:

use std::ops::Deref;

impl<T> Deref for MyStruct<T> {
		type Target = T;
		
		fn deref(&self) -> &Self::Target {
			&self.0  // Assume MyStruct is a single element tuple
		}
}

Note: The method deref shall return a reference. This is to enforce an implicit Deref coercion that will be explained below.

In Rust, there is a policy called Deref coercion. What it does is converts a reference to a type into a reference to another type. For example, Rust will convert &String to &str using &String deref method which return a &str. This policy will be enforced when the reference to a particular type is passed as a function or method argument, but it doesn’t match the required or defined parameter type. Then, Rust will continuously call the deref method down the chain until it can satisfy the requirement, otherwise it will raise a compile error.

There are some restrictions though. Mutable reference (&mut T with DerefMut) can be converted into both mutable reference and immutable reference (&T with Deref). An immutable reference can only be converted into another immutable reference.

Links to this page
  • Rust Trait
  • Rust Smart Pointers

    All smart pointers have 202206221604# trait implemented so that they could be treated like any other reference type in Rust. Meaning, they can use * and & without any significance of syntactic difference from references.

  • Rust Box

    Box<T> is a kind of #202111301656 implemented by Rust standard library which is actually a single element Tuple with 202206221604# and Drop 202204061235#. It doesn’t have performance overhead. It stores data on the 202202062259# rather than on the 202112031157#. We can directly print the value (if it is of simple type) just like other primitive types without dereferencing it. Comparing to normal references, box is pointing to a copied value.

  • Mutex in Rust

    Further inspection into the code, we find out that Mutex offer interior mutability, and can be 202206221604# using the syntax *. It is essentially the same to the 202206232210#. Therefore, one advice is to treat Mutex as if it is a 202111301656# with 202207172210# 202204061235#.

#rust #memory #resource #data-structure