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

Susan Sarandon
Release: 2024-10-31 22:23:29
Original
144 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!