1

Which rule makes the following code work?

struct Dummy(i32);
impl Dummy {
    pub fn borrow(&self) {
        println!("{}", self.0);
    }
}

fn main() {
    let d = Dummy(1);
    (&d).borrow();
    d.borrow();
}

I expect d.borrow() won't work as it passes in self which doesn't match the method signature borrow(&self).

user3461311
  • 95
  • 1
  • 7

1 Answers1

2

From the reference :

A method call consists of an expression (the receiver) followed by a single dot, an expression path segment, and a parenthesized expression-list

When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method.


Note:

Automatic dereference or borrow is only valid for the receiver. If there is no expression as receiver it will not work. Compiler will expect the borrowed type.

Example:

fn main() {
    let d = Dummy(1);

    let borrowed = Dummy::borrow(d);
}

Compiler will show an error:

error[E0308]: mismatched types
  --> src/main.rs:12:34
   |
12 |     let borrowed = Dummy::borrow(d);
   |                                  ^
   |                                  |
   |                                  expected &Dummy, found struct `Dummy`
   |                                  help: consider borrowing here: `&d`
   |
   = note: expected type `&Dummy`
              found type `Dummy`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45