dongtuota3633 2018-04-27 10:01
浏览 29
已采纳

如何找到函数类型的实现?

In Go, it's possible to create function types (https://golang.org/ref/spec#Function_types) like this

type Printer func(s string)

How can I find all of the functions which satisfy this type? For example, if I had the file below, how could I find out that consolePrinter is a Printer?

package main

import "fmt"

func main() {
    printToScreen(consolePrinter)
}

// Printer defines a function that prints a string.
type Printer func(s string)

func printToScreen(p Printer) {
    p("Hello")
}

// consolePrinter is a Printer (the function signature is identical).
func consolePrinter(s string) {
    fmt.Println(s)
}

I tried out guru, but the implements feature doesn't seem to support function types.

guru implements ./main.go:#134
/Users/adrian/go/gurutest/main.go:10.6-10.12: signature type Printer implements only interface{}
  • 写回答

4条回答 默认 最新

  • douhuanchi6586 2018-04-27 11:06
    关注

    You are looking for functions that are assignable to Printer.

    The guru tool does not support an "assignable to" query.

    You can write a program to find functions that are assignable to Printer using the go/types package. Follow the tutorial to type check code and use AssignableTo to find the functions.

    If you are only interested in finding functions declared at package level in gofmted code, then searching your code with a regexp might be good enough. This approach is not accurate, but is simple to do in many editors or the command line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据