使用 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()))
}
结果如下