new 之后会分配内存地址,示例代码:
package main import ( "bytes" "fmt" ) func main() { var buf *bytes.Buffer fmt.Printf("buf init: %p | val: %v ", buf, buf) buf = new(bytes.Buffer) // new 之后会分配内存地址 fmt.Printf("buf after new: %p | val: %v ", buf, buf) fmt.Printf("new buf is nil: %t ", buf == nil) buf.Write([]byte("done! ")) fmt.Printf("buf after write:%p | val: %v ", buf, buf) } // 运行结果: /* MacBook-Pro:new_retVal_aug_15 zhenxink$ go run new_ret_val.go buf init: 0x0 | val: <nil> buf after new: 0xc00005e180 | val: new buf is nil: false buf after write:0xc00005e180 | val: done! MacBook-Pro:new_retVal_aug_15 zhenxink$ */
空指针的 bytes.Buffer 不能直接 Write,示例代码:
package main import ( "bytes" "fmt" ) func main() { var buf *bytes.Buffer buf.Write([]byte("done!")) fmt.Printf("buf val:%v ", buf) } // 运行结果: /* MacBook-Pro:new_retVal_aug_15 zhenxink$ go run nil_buffer_write.go panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x106aec6] goroutine 1 [running]: bytes.(*Buffer).Write(0x0, 0xc000068f63, 0x5, 0x5, 0xc000038778, 0xc000068f78, 0x100508f) /usr/local/go/src/bytes/buffer.go:169 +0x26 main.main() /Users/.../nil_buffer_write.go:10 +0x57 exit status 2 MacBook-Pro:new_retVal_aug_15 zhenxink$ */
// For some types, such as *os.File, nil is a valid receiver, but *bytes.Buffer is not among them.
end...