How to Implement Multiple Interfaces with Identical Method Signatures in Different Packages
Suppose you need to implement interfaces defined in separate packages with conflicting method signatures. This can be challenging, but Go provides a solution.
Let's consider an example:
In package A:
package A type Doer interface { Do() string } func FuncA(doer A.Doer) { // Use doer.Do() here to implement functionality }
In package B:
package B type Doer interface { Do() string } func FuncB(doer B.Doer) { // Use doer.Do() here to implement functionality }
In your main package:
package main import ( "path/to/A" "path/to/B" ) type C int // C implements both A.Doer and B.Doer, but the implementation of Do() aligns with A. func (c C) Do() string { return "C implements both A and B" } func main() { c := C(0) A.FuncA(c) // Acceptable as C implements A.Doer B.FuncB(c) // Error, as the Do() implementation in C doesn't meet B.Doer requirements }
Solution:
To resolve this conflict, Go offers a concise approach:
if _, ok := obj.(A.Doer); ok { }
This allows you to verify if an object (of an interface type) conforms to another interface type (e.g., A.Doer) at runtime.
However, the OP highlights a further complication: the logic implemented for Do() in Package A and Package B is distinct. To address this, create wrappers around your object:
By implementing distinct wrappers, you can control which method to use based on the expected interface type (A.Doer or B.Doer). This eliminates the need for a single Do() method on the original C object, which would struggle to implement both logics.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3