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. ๐ โโ๏ธ