In a Go program, a structure's inability to implement an interface stems from a mismatch between the method parameter types in the structure and the interface.
For a structure to implement an interface, its methods must precisely match the method signatures defined in the interface. This includes not only the method name and return type but also the parameter types.
In the provided code, the Connect method of the D structure takes an (*C) parameter instead of an (A) parameter, as required by the B interface it aims to implement. This mismatch causes the error.
To resolve the issue, the Connect method must be modified to match the interface's signature:
package main import "fmt" type A interface { Close() } type B interface { Connect() (A, error) } type C struct { } func (c *C) Close() { fmt.Println("Closing C") } type D struct { } func (d *D) Connect() (A, error) { c := new(C) return c, nil } func test(b B) { c, _ := b.Connect() fmt.Println("Creating A from B") c.Close() } func main() { d := new(D) test(d) }
With this correction, the D structure now implements the B interface:
func (d *D) Connect() (A, error) { c := new(C) return c, nil }
The above is the detailed content of Why Doesn't My Go Struct Implement the Interface: Mismatched Method Parameters?. For more information, please follow other related articles on the PHP Chinese website!