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.