DEV Community

YellowCoder
YellowCoder

Posted on

Dereferencing Pointer in Rust

Dereferencing refers to the process of accessing the value that a pointer or reference points to. It is done using the dereference operator *

//@yellowcoder  
//example #1

fn main(){

let x = 5;
let y = &x; // y is a reference to x

println!("{}", x);  // Prints: 5
println!("{}", y);  // Prints: 5  (automatically dereferenced)
println!("{}", *y); // Prints: 5  (explicitly dereferenced)

}

Enter fullscreen mode Exit fullscreen mode

In the example above, x is the actual value (5), while y is a reference that points to the memory location where x is stored. When we try to print y directly, we get the memory address. To get the actual value 5, we need to dereference y using *y.

Dereferencing is necessary because Rust's ownership and borrowing rules are designed to ensure memory safety. References are just "views" into the actual data, and they don't own or control the data's lifetime. By requiring explicit dereferencing, Rust ensures that you are aware of when you're accessing the actual data through a reference, rather than the reference itself.

This explicit dereferencing helps catch potential bugs and promotes more readable and safer code, as it clearly distinguishes between working with references and working with the actual values they point to.

In summary, we need to dereference references in Rust to access the actual values they point to, as references themselves are just pointers to memory locations, not the values stored at those locations.

! Have a look on the below example 🧐

//@yellowcoder 
//example #2

fn example(z: &mut i32) {
    *z = 0;  // dereferencing to 0
    println!("value of z -> {}", *z); // Prints: 'value of z -> 0'
}

fn main(){
    println!(&mut 4);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)