gpt4 book ai didi

string - 在 Go 中打印 bytes.Buffer 时的不同行为

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

当我执行此操作时:

buf := new(bytes.Buffer)
buf.WriteString("Hello world")
fmt.Println(buf)

它打印Hello World

但是如果我执行这个:

var buf bytes.Buffer
buf.WriteString("Hello world")
fmt.Println(buf)

它打印:{[72 101 108 108 111 32 119 111 114 108 100] 0 [72 101 108 108 111 32 119 111 114 108 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 0}

我理解这是结构byte.Buffer的内容但为什么它以不同的格式打印?

最佳答案

因为 *bytes.Buffer 类型的值有一个 String() 方法(*bytes.Buffermethod set 包含String() 方法),bytes.Buffer 类型的值则不会。

并且 fmt 包检查正在打印的值是否有 String() string 方法,如果有,则调用它来生成该值的字符串表示形式.

引用自 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:

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

Buffer.String() 方法将其内容作为 string 返回,这就是您在传递 *bytes.Buffer 类型的指针时看到的打印内容。当您传递 bytes.Buffer 类型的非指针值时,它会像普通结构值一样简单打印,默认格式为:

{field0 field1 ...}

查看相关/类似问题:

The difference between t and *t

Why not use %v to print int and string

Why does Error() have priority over String()

关于string - 在 Go 中打印 bytes.Buffer 时的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53005752/

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