Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a variable of arbitrary type is Zero in Golang?

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()
like image 483
v1ct0r Avatar asked Oct 14 '15 03:10

v1ct0r


People also ask

How to find the type of variables in Golang?

There are 3 ways to find the type of variables in Golang as follows: 1 Using reflect.TypeOf Function 2 Using reflect.ValueOf.Kind () Function 3 Using %T with Printf More ...

What does%t mean in Golang?

%T in fmt package is a Go-syntax representation of the type of the value. You can use %T to find the variable type. Note: An empty interface is denoted by interface {} can be used to hold values of any type.

How to check or find the type of an object in go?

4 methods to check or find type of an Object or Variable in Go. To check or find the type of variable or object in Go language, we can use %T string format flag, reflect.TypeOf, reflect.ValueOf.Kind functions. And another method is to use type assertions with switch case.

What does it mean if the structure is empty in Golang?

Last Updated : 04 May, 2020 If the structure is empty means that there is no field present inside that particular structure. In Golang, the size of an empty structure is zero. Whenever the user wants to know if the created structure is empty or not, he can access the structure in the main function through a variable.


1 Answers

Go 1.13 introduced Value.IsZero method in reflect package. This is how you can check for zero value using it:

if reflect.ValueOf(v).IsZero() {
    // v is zero, do something
}

Apart from basic types, it also works for Chan, Func, Array, Interface, Map, Ptr, Slice, UnsafePointer, and Struct.

like image 105
mrpandey Avatar answered Sep 17 '22 17:09

mrpandey