Home > Article > Backend Development > How to Handle Conflicting Method Signatures in Multiple Interfaces?
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.
The above is the detailed content of How to Handle Conflicting Method Signatures in Multiple Interfaces?. For more information, please follow other related articles on the PHP Chinese website!