1

I am in the process of learning rust and it's ownership system, however I seem to have hit a huge obstacle in my learning journey and that is the referencing concept in the language which I've come to understand is similar to the concept of pointers in C.

But pointers in C always require dereferencing to access the things that the pointer is pointing to... that doesn't seem to be the case in rust when calling methods or other functions after a couple of experiments which are shown in the code block below:

fn main()
{
    let mut int = 9; 
    let ptr = &mut int;
    //why is the compiler demanding me to derefrence here
    *ptr += 1;
    //but not here
    println!("ptr: {}", ptr);

    
    let str = String::from("foo");
    let str_ptr = &str;
    //same here, why isn't requiring me to say (*str_ptr).len()
    let len = str_ptr.len();
    println!("String length: {}", len);
}

Is it something to do with how the functions/macros were implemented? Did I understand the whole thing wrong? What is going on here?

  • 1
    Tldr: when you access a member with `thing.member` syntax, Rust automatically dereferences the receiver (`thing`) as many times as it needs to to find `member`. Think of it as like a supercharged `->` from C. This only applies when using receiver (`.`) syntax, not to values in general. – trentcl Apr 14 '21 at 14:48
  • 1
    (although note that [deref coercion](https://stackoverflow.com/q/53341819/3650362) does something superficially similar, in a different context) – trentcl Apr 14 '21 at 15:13

0 Answers0