0

So I can do this:

fn main() {

   let a = 2;
   let b = &a;
   let c = b * 2; // I did not have to de-reference b by typing *b
   dbg!(c);
}

I created b to be a reference (pointer) to a, and I was able to use the value b points to without having to de-reference first.

It works but in trying to understand Rust more, I am curious why this automatic de-referencing occur? And what other scenario can I expect such automatic de-referencing?

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37
  • There is no auto-dereferencing here, [Mul](https://doc.rust-lang.org/std/primitive.i32.html#impl-Mul%3Ci32%3E-for-%26%27a%20i32) trait is also implemented for `&i32`. See [this](https://stackoverflow.com/a/28552082/2642575) answer for details on auto-dereferencing. – Iwa Jan 07 '23 at 13:45
  • @iwa interesting. I just learnt a new thing today. Never knew multiplication has a trait in Rust! To think I hesitated before asking this question because I felt it was a bit obvious and trite! - Do you mind expanding on this as an answer so I can accept it? – Finlay Weber Jan 07 '23 at 13:58
  • I'm not sure, but I think the rationale for implementing arithmetic traits for references such as `&i32` is so that they can work seamless with iterators, such as: `let i = &[i32]; i.iter().fold(1, |a, b| a * b)`. – rodrigo Jan 07 '23 at 14:06
  • @rodrigo I was working with iterators when I found I could work with what I thought were references without de-referencing...that's what led me to ask the question :) – Finlay Weber Jan 07 '23 at 14:08
  • @FinlayWeber [This](https://stackoverflow.com/a/29216923/2642575) may also help. I think I don't have more to add as an answer. – Iwa Jan 07 '23 at 14:24

0 Answers0