在下面的代码中,类型ErrNegativeSqrt
实现了Stringer
和error
接口(interface)。因为在 Sqrt
方法中返回类型是 fmt.Stringer
,所以我认为执行结果是:
0 nil
0 Impl Stringer type
但实际结果是下面的,为什么?
0 nil
0 Impl error type
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func Sqrt(x ErrNegativeSqrt) (float64, fmt.Stringer) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
return 0, nil
}
func (e ErrNegativeSqrt) String() string {
return "Impl Stringer type"
}
func (e ErrNegativeSqrt) Error() string {
return "Impl error type"
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
最佳答案
documentation for Package fmt
指出:
... special formatting considerations apply for operands that implement certain interfaces. In order of application:
...
- If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.
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:
If an operand implements the error interface, the Error method will be invoked ...
If an operand implements method String() string, that method will be invoked ...
由于您使用的是 fmt.Println
,规则 4 和 5 开始发挥作用,它们更喜欢调用 Error()
而不是 String()
关于go - 困惑 : implement multiple interfaces in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058057/