Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 291
Markus Knecht Avatar asked Mar 16 '18 11:03

Markus Knecht


1 Answers

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
    }
}
like image 120
ljedrz Avatar answered Nov 02 '22 12:11

ljedrz