Golang 空指针nil的方法和数据成员

golang中,有一个特殊的指针值nil.

如何使用nil没有方法和成员变量呢?

下面来看下具体例子。

程序中,定义结构体类型Plane, 将Plane类型的指针作为函数的参数,然后传入nil作为实参。
在函数中,使用nil访问Plane的方法。

package main

import (
        "fmt"
)


type Plane struct {
        Num int
}

func (this *Plane) Fly1(){
        fmt.Println("Fly1......")
}

func main(){

        test(nil)
}

func test(pl *Plane) {
        pl.Fly1()
        pl.Fly2()
}

output:

Fly1......

可以看到,正常输出。

添加一个Fly2的方法,定义如下:

func (this *Plane) Fly2(){
        fmt.Println("Fly2......Num:", this.Num)
}
func test(pl *Plane) {
        pl.Fly2()
}

在该方法中,访问Plane的数据成员变量Num.

看下输出结果:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1099302]

goroutine 1 [running]:
main.(*Plane).Fly2(...)
	/Users/lanyang/workspace/mt_go_exercise/t.go:18
main.test(0x0)
	/Users/lanyang/workspace/mt_go_exercise/t.go:28 +0x82
main.main()
	/Users/lanyang/workspace/mt_go_exercise/t.go:23 +0x2a
exit status 2

可以看到,程序crash了。

为什么nil访问方法可以,访问成员变量就会crash呢?

关于nil的定义:

// nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.

var nil Type // Type must be a pointer, channel, func, interface, map, or slice type

指针类型的nil没有分配内存空闲,对于方法,不需要存储空间,而成员变量需要内存空间存放,所以当nil访问成员变量时,由于引用了无效的内存,所以crash.

猜你喜欢

转载自blog.csdn.net/lanyang123456/article/details/102616712