The interface variable in golang is stored by two underlying objects, one is type and the other is value. Only when type and value are both nil, the interface variable is nil
package main
import (
"fmt"
"reflect"
)
type People interface {
Show()
}
type Student struct{
}
func (stu *Student) Show() {
}
func live() People {
var stu *Student
return stu
}
func main() {
i := live()
fmt.Println(reflect.TypeOf(i))
fmt.Println(i)
if i == nil {
fmt.Println("我是为空")
} else {
fmt.Println("我不为空")
}
}
The output is:
You can see the interface variable i, although the value is nil, but the type is Student
If you want to determine whether the variable value is empty, you can specify type
func main() {
i := live()
fmt.Println(reflect.TypeOf(i))
fmt.Println(i)
if i == (*Student)(nil) {
fmt.Println("我是为空")
} else {
fmt.Println("我不为空")
}
}