Go判断对象是否为空结构

在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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值