⚑Smart Pointer

What the hell is Smart Pointer?

What is Pointer & Smart Pointer?

πŸ’‘ A pointer is a variable that stores a memory address. Instead of storing actual data, a pointer acts like an arrow pointing to a specific location in memory where actual data resides.

πŸ’‘ In Rust, the most common type of pointer is a reference (&). It's a borrow checker-enforced way to access data without taking ownership.

fn main() {
    let name = "Thomas";
    let name_ref = &name; // name_ref is a reference containing the memory address of "Thomas"

    println!("Hello, {}", name_ref);
}

πŸ’‘ Smart pointers are data structures that act as a special type of pointer with extra features that automatically manage memory allocation and deallocation. It helps us to manage ownership and borrowing of memory in Rust to ensure resources are allocated and deallocated correctly.

Some common types of smart pointers in Rust

  • Box<T>: It allocates data on the heap and automatically deallocates it when the Box goes out of scope. Useful for storing data on the heap when the size is unknown at compile time.

  • Rc<T> (Reference Counting): It’s a reference-counting smart pointer that allows multiple owners for the same data. The data is deallocated only when the last Rc pointing to it goes out of scope. Useful for shared ownership scenarios.

  • Arc<T> (Atomically Reference Counting): Similar to Rc<T> but used for thread-safe. It’s used for shared ownership across threads.

  • RefCell<T>: It provides interior mutability for borrowed data (normally immutable references can't be modified) which means you can mutate the value even when the Refcell itself is immutable. It enforces borrowing rules at runtime instead of compile time and should be used with caution to avoid data races.

  • Mutex<T> & RwLock<T>: These are used for thread-safe interior mutability. A Mutex provides mutual exclusion, ensuring that only one thread can access the data at a time. An RwLock allows multiple readers or a single writer.

Learn More About Common Types of Smart Pointer

πŸ—³οΈBox<T>β˜„οΈRc<T>🏌️RefCell<T>

Last updated