gpt4 book ai didi

go - 为什么在 Golang 中使用 fmt.Println(slice) 打印 slice 不同

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

代码A:

package main

import "fmt"

func main() {
slice := IntSlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(slice)
}

type IntSlice []int

输出A:

[0 1 2 3 4 5 6 7 8 9]

代码 B:

package main

import "fmt"

func main() {
slice := IntSlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(slice)
}

type IntSlice []int

func (slice IntSlice) Error() string { return "this is called." }

输出B:

this is called.

为什么 fmt.Println(slice) 的行为对于这两个代码(A 和 B)不同?
或者为什么 fmt.Println(slice) 会自动调用 slice.Error()

最佳答案

这是 documented作为 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 the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

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

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

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

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

For compound operands such as slices and structs, the format applies to the elements of each operand, recursively, not to the operand as a whole. Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

fmt 包看到 slice 实现了 error 并打印了 value.Error(),而不是迭代在 slice 上并将格式应用于每个元素。

关于go - 为什么在 Golang 中使用 fmt.Println(slice) 打印 slice 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361397/

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