Home >Backend Development >Golang >How to Implement an Interface with an Interface as Return Type in Go?

How to Implement an Interface with an Interface as Return Type in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-14 17:46:021009browse

How to Implement an Interface with an Interface as Return Type in Go?

Overcoming the Obstacle of Implementing an Interface with an Interface as Return Type in Go

In Go, it's possible to encounter an error when attempting to implement an interface with a return type that is also an interface. This question delves into this issue, providing a solution that resolves the error.

The provided code demonstrates an interface IA with a method FB(), which is expected to return an interface IB. However, the implementation of FB in struct A returns a concrete type *B instead of IB.

To rectify this error, simply modify the return type of FB in struct A to be IB instead of *B:

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

This alteration ensures that A correctly implements the IA interface and resolves the error.

Interfacing Across Packages

The question also inquires about defining interfaces in separate packages. This approach is feasible in Go, allowing you to share interfaces across different packages. However, when the implementation is in a different package, it's necessary to use the fully qualified interface name in the implementation.

For example, if IA and IB are defined in package foo and the implementation is in package bar, the declaration in package bar would be:

type IA interface {
    FB() foo.IB
}

While the implementation in bar would become:

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

This adjustment ensures that the return type of FB matches the expected type specified in the IA interface, regardless of the package in which the interface is defined.

The above is the detailed content of How to Implement an Interface with an Interface as Return Type in Go?. 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