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

How to Print the Method Set of an Interface in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 16:44:021066browse

How to Print the Method Set of an Interface in Go?

How to Print the Method Set of an Interface in Golang

Getting the method set of an interface in Go can be achieved through reflection. This technique allows you to inspect and interrogate the type information of variables without knowing their specific type at compile time.

Solution:

Using the reflect package, you can access the type information and methods of an interface. Here's a code snippet demonstrating how to retrieve the function names for an interface:

<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>

This code will print the following output:

Search
ListSearches
ClearSearches

The reflect.TypeOf() function obtains the type information of the anonymous struct that embeds the interface. Then, t.NumMethod() provides the count of methods defined by the interface, and we iterate over them using t.Method(i).Name to obtain the method names.

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