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.
π‘ 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 theBox
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 lastRc
pointing to it goes out of scope. Useful for shared ownership scenarios.Arc<T>
(Atomically Reference Counting): Similar toRc<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 theRefcell
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. AMutex
provides mutual exclusion, ensuring that only one thread can access the data at a time. AnRwLock
allows multiple readers or a single writer.
Learn More About Common Types of Smart Pointer
Last updated