博客
关于我
Go语言如何判断是否是零值
阅读量:430 次
发布时间:2019-03-06

本文共 629 字,大约阅读时间需要 2 分钟。

通过封装IsZeroOfUnderlyingType方法判断,代码如下

package mainimport (	"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}

转载地址:http://uwlkz.baihongyu.com/

你可能感兴趣的文章
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP、CV 很难入门?IBM 数据科学家带你梳理
查看>>