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
Release: 2025-01-05 15:32:13
Original
843 people have browsed it

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
}
Copy after login

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")
Copy after login

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)
Copy after login

This will output the function type:

func(main.B) string
Copy after login

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() }
Copy after login

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

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

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!

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