Search code examples
rustprivatetraits

How can I avoid a function name clash while implementing a trait?


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?


Solution

  • 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
        }
    }