In this lesson, you’ll learn how to create a custom smart pointer in Rust. Smart pointers are specialized data structures that not only store memory addresses but also manage the underlying resources. They offer advanced features such as reference counting and interior mutability, which enhance resource management. Although Rust provides robust smart pointers like Box<T>, Rc<T>, and RefCell<T> in its standard library, there are scenarios where a customized solution is necessary. We will walk you through the process of building a custom smart pointer by implementing two critical traits: Deref and Drop. The Deref trait allows your smart pointer to behave like a regular reference, while the Drop trait ensures automatic resource cleanup when the pointer goes out of scope.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
The Deref Trait
The Deref trait enables your smart pointer to be used like any other reference. By implementing Deref, you can use the dereference operator (*) to access the data inside the smart pointer, making it compatible in contexts where a regular reference is needed.

MySmartPointer\<T>, that wraps around a value of any type T. The implementation block includes a constructor method that initializes the smart pointer:
*) on an instance of MySmartPointer would not be possible. Below, we implement the Deref trait so that our custom smart pointer behaves like a standard reference:
The Drop Trait
The Drop trait is essential for defining custom behavior when a smart pointer goes out of scope. It allows you to implement cleanup logic for resources such as memory, file handles, or network connections.
MySmartPointer is dropped, the drop method is triggered, which in this example prints a message to indicate that the pointer is being cleaned up.
y falls out of scope at the end of main, Rust automatically calls the drop method, ensuring that any associated resources are properly released.
The sample console output for this code is:Value of y: 5
Dropping MySmartPointer!
Dropping MySmartPointer!
Summary
By implementing the Deref trait, your custom smart pointer works seamlessly as a regular reference, simplifying its integration with functions that expect references. Meanwhile, the Drop trait guarantees automatic cleanup of resources when the smart pointer goes out of scope, ensuring efficient resource management.