0

I just have started learning Rust. While going to some of its examples, I could not understand behaviour of references (Which I loosely relate with pointers).

fn main(){
    let mut s = String::from("abc");
    DoStuff(&mut s);
}

fn DoStuff(reff : &mut String){
    reff.push_str("xyz");       
    (*reff).push_str("xyz");  
    // In the above two lines, why they perform similar actions?
    // as reff and *reff are different types. 
    // *reff should only be able to call pust.str(). But how reff can also call it?


    // reff = String::from("dsf");  -->  Why this will give compile error 
    //                                   if reff & (*reff) behaves somewhat similar for us
    
}

In the above example, both lines

    reff.push_str("xyz");       
    (*reff).push_str("xyz");  

act similar.

As, pust_str() is a method from String. Only (*reff) should be able to call it as per my understanding. Still, reff is also able to call it.

How can I understand this unexpected behaviour?

halfer
  • 19,824
  • 17
  • 99
  • 186
Abhishek
  • 75
  • 7
  • Autodereferencing. – user1937198 Dec 15 '22 at 21:31
  • @user1937198 Is it really auto deref here? `String::push_str` takes `&mut self`, so there's no dereferencing going on IIRC. – SirDarius Dec 15 '22 at 21:46
  • @SirDarius Yes, the real magic is `(*reff)` working. – Chayim Friedman Dec 15 '22 at 21:47
  • @ChayimFriedman my issue here is mostly about semantics I guess. We are indeed invoking dereferencing rules (as explained in the answer [here](https://stackoverflow.com/a/28552082/393701)). However it looks to me as though `(*reff).push_str(...)` does not auto-dereference. It does manual dereferencing, followed by auto-referencing to invoke the method on `&mut self`. If we called instead `reff.into_bytes()` then it would indeed be an auto-deref from `&mut String` to `String`. In the same vein, `reff.as_bytes()` would be an auto-deref to `str`, then an auto-ref to `&str`. – SirDarius Dec 15 '22 at 22:25

1 Answers1

0

Types that implement the Deref trait do automatic dereferencing.

Mostly so you don't have to write (*reff). all the time.

C14L
  • 12,153
  • 4
  • 39
  • 52