Home > Backend Development > Golang > How Can I Detect a 'Real' Interface Implementation in Go Using Reflection?

How Can I Detect a 'Real' Interface Implementation in Go Using Reflection?

Patricia Arquette
Release: 2024-12-23 22:29:19
Original
445 people have browsed it

How Can I Detect a

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

Consider the following code snippet:

type A interface {
  Foo() string
}

type B struct {
  A
  bar string
}
Copy after login

According to Go's idiomatic approach, the pattern above suggests that B must implement the A interface. However, unlike OOP languages, there's no compile-time check for this. Instead, you can opt to implement only part of the interface.

Reflection lets you retrieve methods of A directly from B's type, even if there's no method with receiver B present. However, this raises a question: how can you detect if a "real" implementation exists before triggering a panic?

To solve this, you can't rely on reflection alone. Instead, consider using a straightforward approach:

method_in_table := B.Foo

// Check if the method is nil
if method_in_table == nil {
  fmt.Println("No real implementation found")
} else {
  // Method is present
}
Copy after login

Alternatively, you could use the following reflection-based check:

bType := reflect.TypeOf(B{})
bMeth, has := bType.MethodByName("Foo")
if !has || bMeth.Func.ptr.IsZero() {
  // No real implementation found
} else {
  // Method is present
}
Copy after login

In this scenario, checking if the ptr field of the bMeth function is zero allows you to determine if the function is in the function table of the anonymous interface value. If it's zero, there's no corresponding method in the B struct, indicating a lack of real implementation.

The above is the detailed content of How Can I Detect a 'Real' Interface Implementation in Go Using 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