通過封裝IsZeroOfUnderlyingType方法判斷,代碼如下
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func IsZeroOfUnderlyingType(x interface{}) bool {
return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}
func main() {
var person Person //定義一個零值
fmt.Println(IsZeroOfUnderlyingType(person)) //零值結構體,輸出true
person.Name = "chenqiognhe" //結構體屬性Name賦值
fmt.Println(IsZeroOfUnderlyingType(person)) //輸出false
fmt.Println(IsZeroOfUnderlyingType(person.Age)) //Age仍是零值,輸出true
person.Age = 18 //Age賦值
fmt.Println(IsZeroOfUnderlyingType(person.Age)) //輸出false
}