gpt4 book ai didi

string - 为什么 Error() 优先于 String()

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

我一直在寻找 go 的游览,但我不明白为什么会这样。

当您有一个 Stringer(String() string)时,fmt 将使用该方法打印到控制台。就像 https://tour.golang.org/methods/6 中的建议一样

但是,如果您添加 Error() string,将调用此方法而不是 String() string

package main

import "fmt"

type Person struct {
Name string
Age int
}

func (p *Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

func (p *Person) Error() string {
return fmt.Sprintf("Failed")
}

func main() {
a := &Person{"Arthur Dent", 42}
z := &Person{"Zaphod Beeblebrox", 9001}
fmt.Println(a, z)
}

结果:

Failed Failed

我不明白为什么 fmt.Println 使用 Error 而不是 String

最佳答案

仅仅是因为它是这样实现的。 error 在实践中更为重要,因此如果实现了 error 接口(interface),则会打印出来。

这是文档化的,请阅读 fmt 的包文档:

Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

  1. If an operand implements the Formatter interface, it will be invoked. Formatter provides fine control of formatting.

  2. 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 to convert the object to a string, which will then be formatted as required by the verb (if any).

  2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

因此 error 在列表中排在第 3String() 仅排在第 4

关于string - 为什么 Error() 优先于 String(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30159980/

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