14

Toying with Rust, I'm extracting some code into a class. To keep it self-contained but separate functionality, I want to hang onto a callback function and call it later. To keep it simple, including skipping the obvious fn new(), we have something like:

pub struct Toy {
    go: fn(count: i16) -> String,
}

impl Toy {
    fn lets_go(&mut self, n: i16) -> String {
        self.go(n)
    }
}

Building gives me...

...path.../src/toy.rs:7:14: 7:19 error: type `&mut toy::Toy` does not implement any method in scope named `go`
...path.../src/toy.rs:7         self.go(n)

Presumably, there's a special syntax (or entirely different construct) that makes sense of the self.go() call, but I don't see examples or descriptions of comparable situations in any of the documentation, so I'd appreciate any direction.

Obviously, .go could be of a functor-like class, but that doesn't seem very idiomatic for Rust.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
John C
  • 1,931
  • 1
  • 22
  • 34

1 Answers1

22

foo.bar(...) is always parsed as a method call, it never looks for fields. This avoids ambiguity, especially with traits. One can force it to be a field access by separating the call and the field access into two distinct expressions, for example,

let f = self.go;
f(n)

Or, better, just (self.go)(n).

Issue #2392 covers improving these diagnostics.

huon
  • 94,605
  • 21
  • 231
  • 225
  • Excellent. I should've guessed that parenthesizing would help, but never would have. Thanks! – John C Jan 17 '15 at 00:20