doucongqian6644 2016-05-05 18:46
浏览 273
已采纳

困惑:在Go中实现多个接口

In the below code the type ErrNegativeSqrt implements both Stringer and error interfaces. Since in Sqrt method the return type is fmt.Stringer, I would except the execution result to be:

0 nil

0 Impl Stringer type

But the actual result is the following, why?

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))
}
  • 写回答

2条回答 默认 最新

  • douzhi9939 2016-05-05 19:23
    关注

    The documentation for Package fmt states that:

    ... special formatting considerations apply for operands that implement certain interfaces. In order of application:

    ...

    1. 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:

    1. If an operand implements the error interface, the Error method will be invoked ...

    2. If an operand implements method String() string, that method will be invoked ...

    Since you are using fmt.Println, rules 4 and 5 come into play, which prefers to call Error() over String()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料