go - 困惑 : implement multiple interfaces in Go

标签 go interface

在下面的代码中,类型ErrNegativeSqrt 实现了Stringererror 接口(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:

...

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

由于您使用的是 fmt.Println,规则 4 和 5 开始发挥作用,它们更喜欢调用 Error() 而不是 String()

关于go - 困惑 : implement multiple interfaces in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058057/

相关文章:

c# - 在 C# 中实现 ISP 设计模式

c# - 使用 System.Object 时实现对泛型方法的 new() 约束

c# - 当一个接口(interface)从另一个接口(interface) "inherits"时,你怎么调用它?

mysql - Golang - 将数据插入 MySQL DB 时流意外结束

go - 如何向 Scan 语句添加提示?

performance - 有没有更有效的函数来查找[]字节相似度?

netbeans - 在 NetBeans 中创建接口(interface)实现的快捷方式

datetime - 在 GoLang 中将日期时间 OctetString 转换为人类可读的字符串

go - 如何对支持多个版本的服务器的特定服务进行节俭调用

c# - 当基础类型*可能*不同时,接口(interface)作为属性返回类型?