Home >Backend Development >Golang >Is My Embedded Interface Method 'Real'? Detecting Implemented Methods via Go Reflection

Is My Embedded Interface Method 'Real'? Detecting Implemented Methods via Go Reflection

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 15:32:13810browse

Is My Embedded Interface Method

Go Reflection with Interface Embedded in Struct: Detecting "Real" Functions

When incorporating an embedded interface into a struct (e.g., type B struct { A; bar string }), Go idiomatically suggests that B must implement interface A. However, the reflection package retrieves interface methods directly from B's type, potentially leading to confusion.

To address this, consider the following scenario:

type A interface {
     Foo() string
}

type B struct {
     A
     bar string
}

Suppose we have an instance of B and want to obtain its Foo method using reflection:

bType := reflect.TypeOf(B{})
bMeth, has := bType.MethodByName("Foo")

If has is true, then the following question arises: how can we detect whether there is a "real" implementation of Foo in the returned bMeth?

The provided answer suggests a straightforward approach:

method_in_table := B.Foo
fmt.Printf("%T \n", method_in_table)

This will output the function type:

func(main.B) string

If b.A is nil, as it is by default, then there is no "real" implementation of Foo in the embedded interface. This can be checked using:

if b.A != nil { b.Foo() }

Moreover, the reflection API itself provides mechanisms to detect a nil interface value:

if bMeth.Ptr.IsNil() { // there is no "real" implementation of Foo
}

The above is the detailed content of Is My Embedded Interface Method 'Real'? Detecting Implemented Methods via Go Reflection. 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
Previous article:How to Scan in GoLangNext article:How to Scan in GoLang