Home >Backend Development >Golang >Why Doesn't My Go Struct Implement the Interface?

Why Doesn't My Go Struct Implement the Interface?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 22:39:12411browse

Why Doesn't My Go Struct Implement the Interface?

Interface Implementation Requires Matching Method Signatures

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn