Home >Backend Development >Golang >Does a Go Struct Implement an Interface If a Method Parameter Implements That Interface?

Does a Go Struct Implement an Interface If a Method Parameter Implements That Interface?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 02:46:08555browse

Does a Go Struct Implement an Interface If a Method Parameter Implements That Interface?

Struct Does Not Implement Interface If Its Method Parameter Implements the Interface

In Go, a struct implements an interface if it implements all the methods of that interface. However, if a struct method has a parameter that implements the interface, the struct will not implement the interface.

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) {
    c := new(C)
    return c, nil
}

func test(b B) {
}

func main() {
    d := new(D)
    test(d)
}

In the above example, the struct D does not implement the interface B because the Connect method of D has a parameter that implements the interface A. The error message you are getting is:

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 fix this error, you need to change the type of the parameter in the Connect method of D to A.

type D struct {
}

func (d *D) Connect() (A, error) {
    c := new(C)
    return c, nil
}

Now, the struct D will implement the interface B, and you will be able to call the test() function with a D value as an argument.

The above is the detailed content of Does a Go Struct Implement an Interface If a Method Parameter Implements That 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