首页 > 技术文章 > Go语言如何判断是否是零值

chenqionghe 2020-06-03 16:38 原文

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

推荐阅读