gpt4 book ai didi

Go 函数类型作为接口(interface)值

转载 作者:IT王子 更新时间:2023-10-29 00:43:32 24 4
gpt4 key购买 nike

我一直在阅读 function types as interface values在 go 中,我遇到了一个我无法弄清楚的例子。在这里:

type binFunc func(int, int) int

func add(x, y int) int { return x + y }

func (f binFunc) Error() string { return "binFunc error" }

func main() {
var err error
err = binFunc(add)
fmt.Println(err)
}

您可以在 Go Playground 上找到它 here .

我知道您可以将方法分配给函数类型,但我不明白 Error() 是如何被调用的。

最佳答案

fmt 包的文档是这样说的:

Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

...

If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %v %x %X), the following two rules apply:

  1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
  2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

换句话说,fmt.Println 将尝试打印接口(interface)的字符串表示形式。由于错误接口(interface)由binFunc满足,它调用binFuncError方法。

关于Go 函数类型作为接口(interface)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881328/

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