This is what I’ve found:

In C and C++, two different operators are used for calling methods: you use . if you’re calling a method on the object directly and -> if you’re calling the method on a pointer to the object and need to dereference the pointer first. In other words, if object is a pointer, object->something() is similar to (*object).something().

What about Rust?

Rust doesn’t have an equivalent to the -> operator. Instead, Rust has what is called automatic referencing and dereferencing.

In other words, the following are the same:

p1.distance(&p2); (&p1).distance(&p2); Note: this automatic referencing behavior works because methods have a clear receiver-the type of self. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (&self), mutating (&mut self), or consuming (self).

I am not sureI understood the note correctly, what does it mean that there is a clear receiver? Also, doesn’t Rust actually have an operator for dereferencing (*) as well?

  • TehPers@beehaw.org
    link
    fedilink
    English
    arrow-up
    2
    arrow-down
    1
    ·
    2 days ago

    Everything you said makes sense, but just want to add to your note at the bottom: * can also be used for reborrowing (&*blah, &mut *blah, &***blah, etc). This is useful for getting a shared borrow (&T) or unique/exclusive borrow (&mut T) from another type of pointer (like Box, Arc, or even MutexGuard).