Smart Pointers

A pointer is a general concept for a variable contains an address in memory.

Smart pointers are data structures that not only act like a pointer but also have additional metadata and capabilities.

The concept of smart pointer is usually implemented by using structs. The characteristic that distinguishes smart pointers from ordinary structs is that smart pointers implement the Deref and Drop traits. The Deref trait allows an instance of a smart pointer to behave like a reference so you can write code to work with either references or smart pointers. The Drop trait allows you to customize the code that is run when an instance of the smart pointer goes out of its scope.

Using Box<T> to Point to Data on the Heap

The Box<T> type allows you to store data on the heap rather than on the stack.

Using Box<T> to allocate memory on the heap

fn main() {
    let b = Box::new(5);
}

When b goes out of the scope, it will be deallocated at the end of main, the deallocation happens for the box and the data it points to.

Treating Smart Pointers Like Regular References with the Deref Trait.

Implementing the Deref trait allows you to customize the behavior of the dereference operator, *.

When we want to access the data that a pointer points to, we use the dereference operator * to achieve it.

fn main() {
    let x = 5;
    let y = &x;
    println("{}", *y);
}

Defining Our Own Smart Pointer

The Box<T> type is ultimately defined as a tuple struct with one element.

So we'll define a smart pointer just like it.

struct MyPointer<T>(T);

impl<T> MyPointer<T> {
    fn new(x: T) -> MyPointer<T> {
        MyPointer(x)
    }
}

Treating a Type Like a Reference by Implementing the Deref Trait

use std::ops::Deref;

impl<T> Deref for MyPointer<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

By &self.0 the Deref method returns a reference to the value we want to access with the * operator.

Without the Deref trait, the compiler can only dereference & references. The deref method gives the compiler the ability to make a value of any type that implements Deref and call the deref method to get a & reference that it knows how to dereference.

Implicit Deref Coercions with Functions and Methods

Deref coercion is a convenience that Rust performs on arguments to functions and methods. It only works on types that implement the Deref trait. Deref coercion happens automatically when we pass a reference whose type does not match the type of the argument to a function or a method.

How Deref Coercion Interacts with Mutability

Similar to how you use the Deref trait to override the * operator on immutable references, you can use the DerefMut trait to override the * operator on mutable references.

Rust does deref coercion when it finds types and trait implementations in three cases: