为什么在Golang中使用fmt.Println(slice)打印切片是不同的

为什么在Golang中使用fmt.Println(slice)打印切片是不同的,第1张

概述代码A: package mainimport "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 mainimport "f 代码A:

package mainimport "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 mainimport "fmt"func main() {    slice := IntSlice{0,9}    fmt.Println(slice)}type IntSlice []intfunc (slice IntSlice) Error() string { return "this is called." }

输出B:

this is called.

为什么fmt.Println(切片)的行为对于这两个代码(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:

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.

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

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:

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

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包看到切片实现错误并打印value.Error(),而不是迭代切片并对每个元素应用格式.

总结

以上是内存溢出为你收集整理的为什么在Golang中使用fmt.Println(slice)打印切片是不同的全部内容,希望文章能够帮你解决为什么在Golang中使用fmt.Println(slice)打印切片是不同的所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1267043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存