How can I avoid a collision of a function name when implementing a trait?

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

struct Example {...}

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

Somewhere in another module there is another sign:

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

Now I would like to implement ExampleTraitfor the structure Exampleand redirect the test method to the test implfor the structure.

The following code:

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

Obviously, this is an endless recursive call. I can't just repeat the body of the original test, as I don't have access to the private state Examplehere.

Is there any other way to do this, except by renaming one function or creating fields in Examplepublic?

+4
source share
1 answer

, , :

impl ExampleTrait for Example {
    fn test(&self) {
        Example::test(self) // no more ambiguity
    }
}
+7

Source: https://habr.com/ru/post/1694965/


All Articles