If rust handle dereferencing automatically then why we need explicit dereferencing?

If rust handle dereferencing automatically then why we need explicit dereferencing?

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)

let z = y + 2;    // value is being added to reference
println!("{}",z);  // Prints: 7

Auto-deref doesn't happen everywhere and isn't the correct thing everywhere. Here's one example. Or say...

fn example(mr: &mut i32) {
    *mr = 0;
}

(Incidentally, Display is recursively defined (if T: Display, &T: Display), so you're not actually auto-derefing.)

5 Likes

Thanks Quine :pray:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.