在Go语言中,判断一个对象是否为空结构体可以通过reflect包中的IsZero方法来实现。
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
name string
age uint8
}
func isEmptyStruct(v interface{}) bool {
return reflect.ValueOf(v).Kind() == reflect.Struct && reflect.ValueOf(v).IsZero()
}
func main() {
ms := MyStruct{}
fmt.Println(isEmptyStruct(ms)) //true
ms2 := MyStruct{
name: "Peter",
age: 18,
}
fmt.Println(isEmptyStruct(ms2)) //false
}
此外还可以通过判断类型和零值来判断一个结构体是否为空。
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
name string
age uint8
}
func isEmptyStruct(v interface{}) bool {
t := reflect.TypeOf(v)
if t.Kind() != reflect.Struct {
return false
}
return reflect.DeepEqual(v, reflect.Zero(t).Interface())
}
func main() {
ms := MyStruct{}
fmt.Println(isEmptyStruct(ms)) //true
ms2 := MyStruct{
name: "Peter",
age: 18,
}
fmt.Println(isEmptyStruct(ms2)) //false
}
如果一个对象的结构体中包含其他结构体,可以通过递归方式对这个对象进行判断。
package main
import (
"fmt"
"reflect"
)
type ModelID = uint32
type InputID = uint16
type RangeType uint8
type ColorSpaceType uint8
type ColourGamut uint8
type CscParameter struct {
PortID InputID
HueValue int32
ContrastValue int32
SaturationValue int32
}
type Size struct {
Width int32
Height int32
}
type EdidInfo struct {
Resolution Size
RefreshRate float32
}
type MyStruct struct {
LogicId uint16
ModelId ModelID
HardwareID string
CscParameter CscParameter
EdidInfo EdidInfo
IsEdidSeting bool
IsLimitToFull bool
Range RangeType
ColorSpaceType ColorSpaceType
ColorGamut ColourGamut
}
func IsEmptyStruct(v interface{}) bool {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Struct {
return false
}
for i := 0; i < val.NumField(); i++ {
fieldValue := val.Field(i)
if !fieldValue.IsValid() {
continue
}
switch fieldValue.Kind() {
case reflect.String:
if fieldValue.String() != "" {
return false
}
case reflect.Struct:
if !IsEmptyStruct(fieldValue.Interface()) {
return false
}
default:
if !reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(fieldValue.Type()).Interface()) {
return false
}
}
}
return true
}
func main() {
/* 判断空结构体 */
ms := MyStruct{}
fmt.Println(IsEmptyStruct(ms)) // true
/* 判断非空结构体 */
ms2 := MyStruct{
LogicId: 0,
ModelId: 0,
HardwareID: "",
CscParameter: CscParameter{255, 0, 100, 25},
EdidInfo: EdidInfo{},
IsEdidSeting: false,
IsLimitToFull: false,
Range: 0,
ColorSpaceType: 0,
ColorGamut: 0,
}
fmt.Println(IsEmptyStruct(ms2)) // false
}