英文:
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),则遵循以下两个规则:
- 如果操作数实现了
 error接口,将调用Error方法将对象转换为字符串,然后按照动词(如果有)所需的格式进行格式化。- 如果操作数实现了
 String() string方法,将调用该方法将对象转换为字符串,然后按照动词(如果有)所需的格式进行格式化。
换句话说,fmt.Println将尝试打印接口的字符串表示。由于binFunc满足error接口,它会调用binFunc的Error方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论