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

标签 string pointers go struct

当我执行此操作时:

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/

相关文章:

python-3.x - 使用 python 求解 x

c - 如何限制分配内存的大小?

c++ - 使用指针作为类(class)成员是一种好习惯吗?

json - 已导入包但未在 JSON 解析器中使用

go - 有没有办法知道 channel 缓冲区中有多少消息?

java - 在 Java 中从数组中提取单个随机字符串

arrays - 如何通过特定字符分隔 Swift 3 中的字符串

javascript - 在几个字符之一的第一个实例之后删除所有内容

c语言指针段错误

go - YouTube API : Go client: can't change playlist item position