7

I have a struct with an implementation that has a function which accesses the private state of the struct.

struct Example {...}

impl Example {
    fn test(&self) -> .. {...}
}

Somewhere else in another module there exists another trait:

trait ExampleTrait {
    fn test(&self) -> .. {...}
}

Now I would like to implement ExampleTrait for the Example struct and to forward the test method to the test impl for the struct.

The following code:

impl ExampleTrait for Example {
    fn test(&self) -> .. {
        self.test()
    }
}

Is obviously an infinite recursive call. I cannot just repeat the body of the original test as I do not have access to the private state of Example here.

Is there another way to do this except for renaming one function or making fields in Example public?

ljedrz
  • 20,316
  • 4
  • 69
  • 97
Markus Knecht
  • 430
  • 4
  • 10

1 Answers1

11

You can use the fully-qualified syntax to disambiguate which method is to be used:

impl ExampleTrait for Example {
    fn test(&self) {
        Example::test(self) // no more ambiguity
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ljedrz
  • 20,316
  • 4
  • 69
  • 97
  • is it possible to avoid adding this method stub completely? for instance if a trait has 10 functions which are already derived from another macro/trait, how can I avoid adding this boiler plate? (in other words just add a `impl SomeTrait for MyType {// leave empty since function names coincide and are already implemented}` – Avba Jan 25 '22 at 11:39