Interface Implementation Restrictions on Struct Methods
In Go, a struct can implement an interface only if it has a method with the same name, type, and signature as the interface method. Consider the following code:
package main type A interface { Close() } type B interface { Connect() (A, error) } type C struct { /* ... */ } func (c *C) Close() {} type D struct { /* ... */ } func (d *D) Connect() (*C, error) { return &C{}, nil } // Return type mismatch func test(b B) {} func main() { d := &D{} test(d) // Error: type mismatch for Connect() method }
Here, the error message is: "cannot use d (type D) as type B in argument to test: D does not implement B (wrong type for Connect method)". This occurs because the return type of D's Connect method is *C, which does not match the (A, error) return type specified by the B interface.
Therefore, if a struct's method differs in its parameter or return type from the corresponding interface method, the struct does not implement the interface.
Resolving the Issue
To resolve this issue, the Connect method of struct D must align with the Connect method of interface B. This involves ensuring that it returns the expected (A, error) type.
import "fmt" type A interface { Close() } type B interface { Connect() (A, error) } type C struct { name string } func (c *C) Close() { fmt.Println("C closed") } type D struct {} func (d *D) Connect() (A, error) { return &C{"D"}, nil } func test(b B) { b.Connect().Close() // Call Close() on the returned A } func main() { test(&D{}) }
With this modification, the code compiles and runs without errors, as the Connect method of struct D now adheres to the B interface's definition.
The above is the detailed content of How Do Go Struct Methods Need to Match Interface Definitions to Avoid Type Mismatches?. For more information, please follow other related articles on the PHP Chinese website!