Home > Backend Development > Golang > How to Implement Interface Methods Returning Interfaces in Golang?

How to Implement Interface Methods Returning Interfaces in Golang?

Linda Hamilton
Release: 2024-11-11 06:29:02
Original
355 people have browsed it

How to Implement Interface Methods Returning Interfaces in Golang?

Implementing Interface Method Returning an Interface in Golang

When attempting to implement an interface that returns another interface, a common error arises when the return type of the method does not match the expected type defined in the interface. Consider the following code snippet:

type IA interface {
    FB() IB
}

type IB interface {
    Bar() string
}

type A struct {
    b *B
}

func (a *A) FB() *B {
    return a.b
}

type B struct{}

func (b *B) Bar() string {
    return "Bar!"
}
Copy after login

Running this code will result in the following error:

cannot use a (type *A) as type IA in function argument:
    *A does not implement IA (wrong type for FB method)
        have FB() *B
        want FB() IB
Copy after login

Solution:

The problem lies in the return type of the FB method in the A struct. The IA interface expects FB to return an IB, but in the implementation, it is returning a *B. To rectify this, modify the return type of FB to IB as follows:

func (a *A) FB() IB {
    return a.b
}
Copy after login

Sharing Interfaces Across Packages:

It is possible to define interfaces in different packages and share them. In such cases, when implementing the interface in a struct, the full package path must be used for the return type of the method. For instance, if IA and IB are defined in a package called foo, and the implementation is in a package called bar, the declaration would be:

type IA interface {
    FB() foo.IB
}
Copy after login

And the implementation would be:

func (a *A) FB() foo.IB {
    return a.b
}
Copy after login

The above is the detailed content of How to Implement Interface Methods Returning Interfaces in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template