I have the following in Go:
checkItemState := action.Data.CheckItem.State
if checkItemState != "" {
fmt.Printf("checklist item state: %s", action.Data.CheckItem.State)
}
Now if any of the items in the chain action.Data.CheckItem
are nil/empty, I get a nil pointer dereference error, which makes sense.
But is there a language level way to get checkItemState
if not nil, or ""
if any of the items in the chain are nil/empty.
(I come from Obj-C/Swift land where the nilness propagates)
You can handle this nicely if you code some getters. Go method receivers are just regular function arguments, so it's totally ok to call something on a nil receiver:
type Foo struct {
Name string
}
func (f *Foo) GetName() string {
if f == nil {
return "default name" // or "", whatever
}
return f.Name
}
https://play.golang.org/p/Q20lSo65Kx
This trick is used e.g. by Go protobuf implementation.