1package main
 2
 3type NilReceiverStruct struct {
 4	Value string
 5}
 6
 7func (n *NilReceiverStruct) String() string {
 8	if n == nil {
 9		return "I'm nil!"
10	}
11	return n.Value
12}
13
14func (n *NilReceiverStruct) PanicIfNil() string {
15	return n.Value
16}
17
18func main() {
19	var n *NilReceiverStruct = nil
20	println("n.String() =", n.String())         // n.String() = I'm nil!
21	println("n.PanicIfNil() =", n.PanicIfNil()) // panic: runtime error: invalid memory address or nil pointer dereference
22}
nilnil

panic: runtime error: invalid memory address or nil pointer dereference

内容声明

标题: Golang 指针方法接收器是可以为 nil 的

链接: https://zixizixi.cn/golang-methods-on-pointers-receiver-can-be-nil