gpt4 book ai didi

go - 困惑 : implement multiple interfaces in Go

转载 作者:IT王子 更新时间:2023-10-29 01:49:40 24 4
gpt4 key购买 nike

在下面的代码中,类型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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com