如何知道Golang中任意类型的变量是否为零? [英] How to know if a variable of arbitrary type is Zero in Golang?

查看:164
本文介绍了如何知道Golang中任意类型的变量是否为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为并非所有类型都具有可比性,例如一片。所以我们不能这样做
$ b $ pre $ var $ ArbitraryType
v == reflect.Zero(reflect.TypeOf(v) ).Interface()

编辑 - 解决方案reflect.DeepEqual

  var v ArbitratyType 
zero:= reflect.Zero(reflect.TypeOf(v))。Interface()
转到文档关于 reflect.DeepEqual


DeepEqual测试为了深刻的平等。它在可能的情况下使用普通的==相等性,但会扫描数组,切片,地图和结构字段的元素。


解决方案

.ValueOf(v)== reflect.Zero(reflect.TypeOf(v)))

reflect.DeepEqual(reflect.ValueOf(v),reflect.Zero(reflect.TypeOf(v)))

例如各种整数0口味和未初始化 struct s是零

可悲的是,空字符串和数组不是。和 nil 会产生一个异常。

如果您想要的话,您可以特别注意这些。


Because not all types are comparable, e.g. a slice. So we can't do this

var v ArbitraryType
v == reflect.Zero(reflect.TypeOf(v)).Interface()

Edit - Solution reflect.DeepEqual

var v ArbitratyType
zero := reflect.Zero(reflect.TypeOf(v)).Interface()
isZero := reflect.DeepEqual(v, zero)

Go documentation about reflect.DeepEqual

DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs.

解决方案

Both of the following give me reasonable results (probably because they're the same?)

reflect.ValueOf(v) == reflect.Zero(reflect.TypeOf(v)))

reflect.DeepEqual(reflect.ValueOf(v), reflect.Zero(reflect.TypeOf(v)))

e.g. various integer 0 flavours and uninitialized structs are "zero"

Sadly, empty strings and arrays are not. and nil gives an exception.
You could special case these if you wanted.

这篇关于如何知道Golang中任意类型的变量是否为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆