Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: How to check if a struct property was explicitly set to a zero value?

Tags:

go

type Animal struct {
    Name string
    LegCount int
}

snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}

Question: How can I check snake and worm after they've been set, to tell that:

  1. snake was explicitly set with a LegCount of 0.
  2. The worm's LegCount was not explicitly set (and therefore based off of its default value)?
like image 560
Nathan Lippi Avatar asked Mar 15 '16 14:03

Nathan Lippi


People also ask

How do you check if a struct is empty?

1) To check if the structure is empty:fmt. Println( "It is an empty structure." ) fmt. Println( "It is not an empty structure." )

What is the zero value of a struct in Golang?

A zero value struct is simply a struct variable where each key's value is set to their respective zero value. This article is part of the Structs in Go series. We can create a zero value struct using the var statement to initialize our struct variable.

What is the default value of struct in Golang?

Struct types The default zero value of a struct has all its fields zeroed.


1 Answers

It is simply impossible to distinguish.

If you are unmarshalling data from XML or JSON, use pointers.

type Animal struct {
    Name *string
    LegCount *int
}

You will get nil values for absent fields.

You can use the same convention in your case.

like image 65
Grzegorz Żur Avatar answered Sep 18 '22 16:09

Grzegorz Żur