最近写go语言程序的时候,发现了一个问题。先看代码:
// MusicPlay project main.go
package main
import (
"fmt"
)
type Cat interface {
Meow()
}
type Tabby struct{}
func (*Tabby) Meow() { fmt.Println("meow") }
func GetACat() Cat {
var myTabby *Tabby = nil
// Oops, we forgot to set myTabby to a real value
return myTabby
}
func TestGetACat() {
var ICat Cat
var tabby *Tabby = nil
ICat = tabby
//ICat = GetACat()
//ICat = nil
if ICat == nil {
fmt.Println("GetTest Failed!")
}
}
func main() {
TestGetACat()
}
在调用TestGetACat()函数中,我的想法是ICat应该为nil,然后调用fmt.Println("GetTest Failed!")。运行结果却是没有调用,这个顿时我就感觉有点迷惑了,然后直接加上ICat = nil却又是可以的,于是乎百度了一下。发现了一遍文章,地址:http://geek.csdn.net/news/detail/102187。
他的理解是这样的: ICat指向一个Tabby指针对象,该指针指向nil。所以ICat不为nil。
暂时只能够这么理解,记录下来