通过封装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
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-06
  • 2022-01-07
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2021-11-28
  • 2021-11-28
  • 2021-12-10
  • 2022-01-03
相关资源
相似解决方案