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

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证