DEV Community

YellowCoder
YellowCoder

Posted on

2 1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay