gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:41 25 4
gpt4 key购买 nike

在 Go 中,可以像这样创建函数类型 (https://golang.org/ref/spec#Function_types)

type Printer func(s string)

如何找到满足该类型的所有函数?例如,如果我有下面的文件,我如何才能发现 consolePrinter 是一个 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)
}

我试用了 guru,但 implements 功能似乎不支持函数类型。

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

最佳答案

您正在寻找 assignable 的函数到打印机

guru 工具不支持“assignable to”查询。

您可以编写一个程序来使用 go/types 查找可分配给 Printer 的函数包裹。关注tutorial输入检查代码并使用 AssignableTo找到函数。

如果您只对在 gofmted 代码中查找在包级别声明的函数感兴趣,那么使用正则表达式搜索您的代码可能就足够了。这种方法不准确,但在许多编辑器或命令行中很容易实现。

关于go - 如何找到函数类型的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50059956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com