go 判断是否为0值

  • 2023-08-23 09:27:12
  • 阅读:73次

使用 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()))
}

结果如下

热门内容