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

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

Susan Sarandon
Susan SarandonOriginal
2024-10-31 22:23:29128browse

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

Accessing Method Set of an Interface in Golang

Determining the methods within an interface can be useful for various scenarios. This article explores how to effectively print the method set of an interface in Golang.

Challenge

Given the following interface:

<code class="go">type Searcher interface {
    Search(query string) (found bool, err error)
    ListSearches() []string
    ClearSearches() (err error)
}</code>

How can we print the names of these methods (Search, ListSearches, and ClearSearches) without prior knowledge of a concrete type implementing the interface?

Solution

The reflect package provides the means to inspect types at runtime. By leveraging this package, we can retrieve the type information of our interface and examine its methods.

<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 achieves our goal by reflecting on the interface type and iterating over its methods to print their names.

Output

Running this program will produce the desired output:

Search
ListSearches
ClearSearches

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