The Curious Case of Different Print Outputs: *bytes.Buffer vs. bytes.Buffer
When working with bytes in Go, understanding the subtle differences between pointer and non-pointer values can lead to unexpected print results.
When you execute the following code:
buf := new(bytes.Buffer) buf.WriteString("Hello World") fmt.Println(buf)
You get the familiar output: "Hello World". This is because, for pointer values like *bytes.Buffer, Go checks if the value has a String() method. In this case, *bytes.Buffer implements String(), and its invocation results in the buffer's contents being printed as a string.
However, the same code executed for non-pointer values like bytes.Buffer behaves differently:
var buf bytes.Buffer buf.WriteString("Hello World") fmt.Println(buf)
Instead of the expected string representation, you get the following output:
{[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
This seemingly cryptic output represents the memory layout of the bytes.Buffer struct, including its fields and padding bytes.
The reason for this difference lies in the way Go handles printing of values. It checks if the value being printed has a String() method, and if so, uses it to obtain a string representation. For the pointer type *bytes.Buffer, the String() method is present, and thus its contents are printed as a string. For the non-pointer type bytes.Buffer, however, the String() method is not implemented, leading to the default formatting of its individual fields.
It's important to keep this distinction in mind to avoid surprises when working with bytes and buffers in Go. Understanding the different behaviors of pointer and non-pointer values will help you write more predictable and robust code.
The above is the detailed content of Why Does `fmt.Println` Show Different Outputs for `*bytes.Buffer` and `bytes.Buffer` in Go?. For more information, please follow other related articles on the PHP Chinese website!