Załóżmy, że muszę zaimplementować dwa różne interfejsy zadeklarowane w dwóch różnych pakietach (w dwóch różnych oddzielnych projektach).Jak zaimplementować dwa różne interfejsy o tym samym metodzie podpisu
mam w pakiecie A
package A
type interface Doer {
Do() string
}
func FuncA(Doer doer) {
// Do some logic here using doer.Do() result
// The Doer interface that doer should implement,
// is the A.Doer
}
aw pakiecie B
package B
type interface Doer {
Do() string
}
function FuncB(Doer doer) {
// some logic using doer.Do() result
// The Doer interface that doer should implement,
// is the B.Doer
}
W moim main
pakietu
package main
import (
"path/to/A"
"path/to/B"
)
type C int
// this method implement both A.Doer and B.Doer but
// the implementation of Do here is the one required by A !
func (c C) Do() string {
return "C now Imppement both A and B"
}
func main() {
c := C(0)
A.FuncA(c)
B.FuncB(c) // the logic implemented by C.Do method will causes a bug here !
}
Jak radzić sobie z tą sytuacją?
Nie ma absolutnie nic do czynienia z: ** Dowolny ** typ, który ma metodę 'Do() string' implementuje * oba * interfejsy' A.Doer' i 'B.Doer'. – Volker
Myślę, że masz rację: @Volker, nie ma na to poprawki, a ta sytuacja może wystąpić w każdym języku, który używa interfejsów (na przykład 'java'). – tarrsalah