这是一个空值struct nil
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?
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))
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{}
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.