Member-only story
Exploring the Box Wrapper (Smart Pointers ) in Rust — In depth with examples!
I was struggling with Box, Ref, RefCell, Rc, Arc for a while when I decided that I need to implement each one of them to really understand them. To do this, I played with Box type on both primitive and non primitive data types. This article is all about my understanding of the Box
wrapper type along with an example for each.
What is a Box Type
All at the very basic level, Box
is a way of initializing values on the Heap. In other words, its a Smart Pointer. It’s like Initializing a value and having a pointer in C / C++ / Java ( Rust style, of course ). To initialize a Box type, we just use the Box::new(T)
associated type, and pass in any value that needs to be on the heap.
To understand Box type, we first need to know how to check the address of any variable. Before diving deeper, let’s take a look at printing memory addresses of variables. Refer to the following program
fn main() {
let i : i32 = 10 ;
let j = i ;
println!("Address of variable i is {:p}",&i);
println!("Address of variable j is {:p}",&j);
}
Let’s take a look at an example by defining an integer and try printing its address. Running this program will give us the address of the variable i.