首页 > 其他分享 >go 判断是否为0值

go 判断是否为0值

时间:2023-02-28 16:35:50浏览次数:34  
标签:判断 %+ 是否 fmt testStruct reflect Active Zero go

使用 reflect.Zero 方法
示例代码如下

package main

import (
	"fmt"
	"reflect"
)

type TestStruct struct {
	Num    int
	Active bool
	Name   string
}

// 判断是否为0值
func main() {
	// 判断bool 是否为0值
	var b bool
	fmt.Printf("b is zero? result is  %+v \n", reflect.DeepEqual(b, reflect.Zero(reflect.TypeOf(b)).Interface()))

	// 判断 struct 是否为0值
	testStruct := TestStruct{}
	fmt.Printf("testStruct is zero? result is  %+v \n", reflect.DeepEqual(testStruct, reflect.Zero(reflect.TypeOf(testStruct)).Interface()))
	testStruct.Num = 111
	fmt.Printf("testStruct is zero? result is  %+v \n", reflect.DeepEqual(testStruct, reflect.Zero(reflect.TypeOf(testStruct)).Interface()))

	fmt.Printf("testStruct.Active is zero ? result is  %+v \n", reflect.DeepEqual(testStruct.Active, reflect.Zero(reflect.TypeOf(testStruct.Active)).Interface()))
	testStruct.Active = true
	fmt.Printf("testStruct.Active is zero ? result is  %+v \n", reflect.DeepEqual(testStruct.Active, reflect.Zero(reflect.TypeOf(testStruct.Active)).Interface()))
}

结果如下

标签:判断,%+,是否,fmt,testStruct,reflect,Active,Zero,go
From: https://www.cnblogs.com/ifnk/p/17164780.html

相关文章