Understanding Dereferencing in Rust

Understanding Dereferencing in Rust

Dereferencing is how we access the value that a reference points to. References are like signposts that guide us to the actual data.

Imagine them as arrows pointing to a treasure! ๐Ÿ’Ž Technically, a pointer stores the address of another variable in memory. So, if we do something like the example below:

fn main(){
  let x = 42; 
  let my_ref = &x;
}

my_ref will hold the address of x in memory. In that case, x is not equal to my_ref, make sense?

So, in some cases, you might want to use the value my_ref is holding a reference to, that is where dereferencing comes into play.

The * symbol is the key to getting the value my_ref is pointing to. Weโ€™ll add it before the reference variable `my_ref` and be like: “Hey big man, Rust, give me the actual value, not the reference!”

Example:


fn main(){
   let x = 42; 
   let my_ref = &x; 
   let value = *my_ref; 
   println!("Value: {}", value); // Output: Value: 42
}

Also, Rust makes sure to keep things safe. So, if you try to dereference a null reference, it will panic โ€” as you already know. Rust won’t let you access something that might not even exist. ๐Ÿ™…โ€โ™‚๏ธ

Buy Me A Coffee

Published by Eze Sunday Eze

Hi, welcome to my blog. I am Software Engineer and Technical Writer. And in this blog, I focus on sharing my views on the tech and tools I use. If you love my content and wish to stay in the loop, then by all means share this page and bookmark this website.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.