Home > Backend Development > Golang > How to Implement Interface Methods with Interface Return Types in Go?

How to Implement Interface Methods with Interface Return Types in Go?

Susan Sarandon
Release: 2024-11-09 15:12:02
Original
563 people have browsed it

How to Implement Interface Methods with Interface Return Types in Go?

Implementing Interface Method with Interface Return Type in Go

In Go, one may encounter a situation where an interface method has an interface as its return type. This raises the question of how to implement such a method.

Consider the example code provided:

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

When attempting to compile this code, an error occurs because the A struct's FB method returns a *B concrete type instead of the required IB interface type.

To resolve this issue, simply modify the FB method in the A struct to return the IB interface type:

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

Now, the A struct correctly implements the IA interface and can be used as an IA type.

In cases where the interfaces are defined in different packages, it is still possible to implement the method appropriately. For example, if IA and IB are defined in package foo and the implementations are in package bar, the declaration and implementation would be as follows:

Declaration (in foo package):

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

Implementation (in bar package):

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

By casting the returned value to the required interface type, the implementation can conform to the required interface and compile successfully.

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