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?

  • @[email protected]
    link
    fedilink
    English
    73 days ago

    By clear receiver it means there is only one function a name can point to. For instance you cannot have:

    struct Foo;
    impl Foo {
        pub fn foo(self) {}
        pub fn foo(&self) {}
    }
    
    error[E0592]: duplicate definitions with name `foo`
     --> src/lib.rs:5:5
      |
    4 |     pub fn foo(self) {}
      |     ---------------- other definition for `foo`
    5 |     pub fn foo(&self) {}
      |     ^^^^^^^^^^^^^^^^^ duplicate definitions for `foo`
    

    Which means it is easy to see what the function requires when you call it. It will either have self or &self and when it is &self it can auto reference the value for you. This is unlike C and C++ where you can overload a function definition with multiple different signatures and bodies and thus the signature is important to know to know which function to actually call.


    Yes rust has a operator for dereferencing as well (the *). This can be used to copy a value out of a reference for simple types the implement Copy at least.

    • Ephera
      link
      fedilink
      English
      42 days ago

      And if you’re wondering, what the hell, if there’s no overloading, how do you even design an API???
      You’ll learn about the From and Into traits, which allow you to take multiple types for a parameter, because those traits implement the conversion between those types.

      • @[email protected]
        link
        fedilink
        4
        edit-2
        2 days ago

        If you want polymorphism which looks more like what you’re describing, you can put trait bounds on parameters instead of a type and it will accept any parameter that implement those traits. E.g. If you want to accept anything that can be turned into an owned string with “.into()” you type an argument with “impl Into<String>”. Another common one is “impl AsRef<Path>” to accept a path, path reference, PathBuf etc.