dozc58418381 2016-07-13 20:47
浏览 3265
已采纳

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

code 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

output A:

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

code 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." }

output B:

this is called.

why the behavior of fmt.Println(slice) is different for these two codes( A and B)?
or why fmt.Println(slice) calls slice.Error() automatically?

  • 写回答

1条回答 默认 最新

  • dqqpf32897 2016-07-13 20:54
    关注

    This is documented as part of the behaviour of fmt (emphasis mine):

    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.

    The fmt package sees that slice implements error and prints value.Error(), rather than iterating over the slice and applying formatting to each element.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格