Home > Backend Development > Golang > How to Retrieve the Method Set of an Interface in Golang?

How to Retrieve the Method Set of an Interface in Golang?

Barbara Streisand
Release: 2024-11-02 03:31:03
Original
1095 people have browsed it

How to Retrieve the Method Set of an Interface in Golang?

How to Retrieve Method Set of an Interface in Golang

Determing the method set of an interface in Golang helps you obtain a list of all the methods a specific interface enforces. To achieve this, we employ the reflect package.

Method Set Extraction Using Reflection

Without prior knowledge of the implementing concrete type, you can use the following code snippet to print the method set:

<code class="go">package main

import (
    "fmt"
    "reflect"
)

type Searcher interface {
    Search(query string) (found bool, err error)
    ListSearches() []string
    ClearSearches() (err error)
}

func main() {
    t := reflect.TypeOf(struct{ Searcher }{})
    for i := 0; i < t.NumMethod(); i++ {
        fmt.Println(t.Method(i).Name)
    }
}</code>
Copy after login

Using reflection, we obtain the reflect.Type of the anonymous struct that conforms to the interface. The NumMethod() function retrieves the total number of methods defined by the interface, and the loop iterates through each method, printing its name.

Running the code snippet will produce the following output:

Search
ListSearches
ClearSearches
Copy after login

This method set extraction technique proves useful when you need to work with interfaces dynamically without knowledge of the implementing types.

The above is the detailed content of How to Retrieve the Method Set of an Interface in Golang?. 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