Here is the code for the problem. comparing the two buffer types shows they are not equal but two *File types are equal.
func main() {
var v, w io.Writer
v := &bytes.Buffer{}
w := &bytes.Buffer{}
v.Write([]byte("Hello"))
w.Write([]byte("Hello"))
fmt.Println(v == w) // false
v := os.Stdout
w := os.Stdout
v.Write([]byte("Hello"))
w.Write([]byte("Hello"))
fmt.Println(v == w) // true
}
CodePudding user response:
You are comparing pointers, not objects. The expression &bytes.Buffer{} creates a new object in memory and returns a pointer to it. Doing that twice would give two different pointers, since no two objects can reside at the same memory location.
To compare the actual contents of buffers, use something like bytes.Compare(v.Bytes(), w.Bytes())
v := &bytes.Buffer{}
w := &bytes.Buffer{}
v.Write([]byte("Hello"))
w.Write([]byte("Hello"))
fmt.Printf("%p, %p\n", v, w) // prints 2 different values
fmt.Println(bytes.Compare(v.Bytes(), w.Bytes())) // 0, means "equal"
Regarding the second case, os.Stdout is a global variable containing a pointer to os.File, so the snippet compares two pointers to the same object.
v := os.Stdout
w := os.Stdout
v.Write([]byte("Hello"))
w.Write([]byte("Blah!")) // doesn't matter
fmt.Println(v == w) // true: v and w point to the same object!
