Home >Backend Development >Golang >Why Doesn't My Go Struct Implement the Interface?
In Go, interfaces dictate the structure of a method, including its name, arguments, and return values. When a struct implements an interface, it must strictly adhere to the method signatures specified by the interface.
Consider this example where a struct, D, and its method, Connect, fail to implement the interface B due to a mismatch in the return value:
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) { // Mismatched function signature compared to interface B's Connect method c := new(C) return c, nil }
In this case, Connect in D returns a pointer to C and an error, but the interface B expects Connect to return an implementation of A and an error. Therefore, the error states that the struct D does not implement the interface B, highlighting the importance of alignment between the method signatures.
cannot use d (type *D) as type B in argument to test: *D does not implement B (wrong type for Connect method) have Connect() (*C, error) want Connect() (A, error)
To resolve this issue, ensure that the method signatures in the struct implementation match the method declarations in the interface. In this scenario, the Connect method in D should be modified to comply with the B interface:
func (d *D) Connect() (A, error) { c := new(C) return c, nil }
In contrast, if the method signature in the struct implementation differs from the interface, the struct will not implement the interface.
type Equaler interface { Equal(Equaler) bool } type T int func (t T) Equal(u T) bool { // Argument type mismatch return t == u } // does not satisfy Equaler
In this example, the argument type in Equal should match the interface type Equaler instead of a different type, T, to implement the interface correctly.
The above is the detailed content of Why Doesn't My Go Struct Implement the Interface?. For more information, please follow other related articles on the PHP Chinese website!