Go Function Types as Interface Values

huangapple go评论77阅读模式
英文:

Go 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上找到这个例子的链接:这里

我理解你可以将一个方法赋值给一个函数类型,但是我不明白Error()是如何被调用的。

英文:

I have been reading about function types as interface values in go and I came across an example that I have not been able to figure out. Here it is:

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

You can find it on Go Playground here.

I understand that you can assign a method to a function type, but I do not understand how Error() is being called.

答案1

得分: 6

fmt包的文档中有这样的说明:

除非使用%T%p这两个动词打印,否则对于实现了特定接口的操作数,会应用特殊的格式化考虑。按照应用的顺序:

...

如果格式(对于Println等隐式为%v)对于字符串有效(%s %q %v %x %X),则遵循以下两个规则:

  1. 如果操作数实现了error接口,将调用Error方法将对象转换为字符串,然后按照动词(如果有)所需的格式进行格式化。
  2. 如果操作数实现了String() string方法,将调用该方法将对象转换为字符串,然后按照动词(如果有)所需的格式进行格式化。

换句话说,fmt.Println将尝试打印接口的字符串表示。由于binFunc满足error接口,它会调用binFuncError方法。

英文:

The docs for the fmt package have this to say:

> 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:
>
> 4. 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).
> 5. 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).

In other words, fmt.Println will attempt to print the string representation of the interface. Since the error interface is satisfied by binFunc, it invokes the Error method of binFunc.

huangapple
  • 本文由 发表于 2017年3月19日 07:58:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42881328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定