直接看代码
package test
import (
"fmt"
"testing"
)
type StructA struct {
str string
}
func NewStructA() *StructA {
return nil
}
type InterfaceA interface{}
func ToInterfaceA() InterfaceA {
return NewStructA() // NewStructA return nil
}
func ReturnInterface() InterfaceA {
return nil
}
func TestXXX(t *testing.T) {
a := ReturnInterface()
fmt.Println(a == nil) // true
fmt.Printf("type of a %T\n", a) // type of a <nil>
b := NewStructA()
fmt.Println(b == nil) // true
fmt.Printf("type of b %T\n", b) // type of b *test.StructA
c := ToInterfaceA()
fmt.Println(c == nil) // false
fmt.Printf("type of c %T\n", c) // type of c *test.StructA
}
为什么 c == nil 是false?
Interface类型由value和type两部分组成,。type是接口的基础具体类型,value是具体类型的值:
认为c是Interface类型的依据:
Go中认为实现了一个接口就是拥有这个接口的所有函数,这个程序中InterfaceA接口是一个空的接口,没有函数,所以所有类型都实现了这个接口,当然也包括指针,所以在ToInterfaceA的返回值才没有报错。如果认为ToInterfaceA函数返回的一个指针类型的话,可以在InterfaceA中增加一个Name函数,StructA不实现这个函数的话,程序是会报错的。
(目前也在学习GO,错了的话,嗯~~~~请谅解。)