1

Is there a generic way to test a variable for initial in Go?

Given these test:

package main

import "fmt"

type FooStruct struct {
    A string
    B int
}

type BarStruct struct {
    A string
    B int
    C map[int]string
}

func main() {
    // string isinital test
    var s string
    fmt.Println(s == "")

    // int isinital test
    var i int
    fmt.Println(i == 0)

    // primitive struct isinital test
    var fp FooStruct
    fmt.Println(fp == FooStruct{})

    // complex struct isinital test
    // fail -> invalid operation: fc == BarStruct literal (struct containing map[int]string cannot be compared)
    var fc BarStruct
    fmt.Println(fc == BarStruct{})

    // map isinital test
    var m map[string]int
    fmt.Println(len(m) == 0)

    // map isinital test 
    // fail -> invalid operation: m == map[string]int literal (map can only be compared to nil)
    fmt.Println(m == map[string]int{})
}

A: What is the proper way to test BarStruct for initial?

B: Is there a generic way to test any var for is initial?

RickyA
  • 15,465
  • 5
  • 71
  • 95

1 Answers1

1

You can use reflect.DeepEqual:

bs := BarStruct{}
fmt.Println(reflect.DeepEqual(bs, BarStruct{}))
// Output:
//   true

Playground: http://play.golang.org/p/v11bkKUhXQ.

EDIT: you can also define an isZero helper function like this:

func isZero(v interface{}) bool {
    zv := reflect.Zero(reflect.TypeOf(v)).Interface()
    return reflect.DeepEqual(v, zv)
}

This should work with any type:

fmt.Println(isZero(0))
fmt.Println(isZero(""))
fmt.Println(isZero(bs))
fmt.Println(isZero(map[int]int(nil)))
Ainar-G
  • 34,563
  • 13
  • 93
  • 119