Look at the following code snippet.
package main
import "fmt"
type Empty struct {
Field1, Field2 string
}
func main() {
value := Empty{}
fmt.Println(value == nil)
fmt.Printf("%p", &value)
}
I've got compiler error
./empty_struct.go:19: cannot convert nil to type Empty
How can I check a value struct type, if it is empty or not?
An empty struct is a struct type without fields struct{} . The cool thing about an empty structure is that it occupies zero bytes of storage. You can find an accurate description about the actual mechanism inside the golang compiler in this post by Dave Chaney.
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.
Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.
An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.
Yes, it is allowed in C programming language that we can declare a structure without any member and in that case the size of the structure with no members will be 0 (Zero). It will be a Zero size structure.
Pointers, slices, channels, interfaces and maps are the only types that can be compared to nil. A struct value cannot be compared to nil.
If all fields in the struct are comparable (as they are in your example), then you can compare with a known zero value of the struct:
fmt.Println(value == Empty{})
If the struct contains fields that are not comparable (slices, maps, channels), then you need to write code to check each field:
func IsAllZero(v someStructType) bool {
return v.intField == 0 && v.stringField == "" && v.sliceField == nil
}
...
fmt.Println(isAllZero(value))
You can define a "nil" value of a struct, for example:
var nilEmpty = Empty{}
fmt.Println(value == nilEmpty)
nil
can only be used for pointer-types (slices, channels, interfaces and maps).
Keep in mind that struct equality doesn't always work if you have slices or any incomparable value in the struct, you would have to use reflect.DeepEqual
then.
From http://golang.org/ref/spec#Comparison_operators:
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
It is a value type, like int
, therefore it cannot be nil. Only pointer and interface types can be nil. If you want to allow a nil value, make it a pointer:
value := &Empty{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With