【问题标题】:How to determine the method set of an interface in Golang?Golang中如何确定接口的方法集?
【发布时间】:2016-08-05 22:33:56
【问题描述】:

如何打印以下接口的方法集?

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

这样

Search
ListSearches
ClearSearches

打印出来了吗? (不知道实现它的具体类型)。

【问题讨论】:

  • 问题是,如何打印方法。因此,简单的解决方案是: godoc 。搜索器(如果您想询问不是当前包,请将 . 替换为包的名称)

标签: go interface


【解决方案1】:

reflect 包是解决此问题的正确工具。使用反射可以在事先不知道变量类型的情况下获取变量的类型信息。这是一段代码sn-p,展示了如何获取接口根据需要定义的函数的函数名

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

查看golangplayground

【讨论】:

    【解决方案2】:

    使用反射:

    t := reflect.TypeOf(new(Searcher)).Elem()
    fmt.Println(t)
    
    for i := 0; i < t.NumMethod(); i++ {
        fmt.Println(t.Method(i).Name)
    }
    

    打印:

    main.Searcher
    ClearSearches
    ListSearches
    Search
    

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 2023-03-06
      • 2016-11-18
      • 2019-06-02
      • 2012-08-08
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多