A question to you: how less verbose you want to get? Because you want to do different things on different conditions (different fields being nil
). Your code contains these different things and the different conditions. Beyond that what's "redundant" in your code are just the switch
and case
keywords. You want to leave them out? Because the rest is not "redundant", they are required.
Also note that in Go case
s do not fall through even without a break
(unlike in other languages), so in your above example if f.Baz
is nil
, you will set it to 42
and f.Qux
will not be checked (so no error
will be returned), but if f.Baz
is non-nil
and f.Qux
is nil
, an error
will be returned. I know it's just an example, but this is something to keep in mind. You should handle error
s first if you use a switch
! Or use if
statements and then the error will be detected and returned regardless of the order of field checks.
Your code with switch
is clean and efficient. If you want to make it less verbose, readability (and performance) will suffer.
You may use a helper function which checks if a pointer value is nil
:
func n(i interface{}) bool {
v := reflect.ValueOf(i)
return v.Kind() == reflect.Ptr && v.IsNil()
}
And using it:
func check(f *Foo) error {
switch {
case n(f.Bar):
return errors.New("Missing 'bar'")
case n(f.Qux):
return errors.New("Missing 'qux'")
case n(f.Baz):
x := int64(42)
f.Baz = &x
}
return nil
}
Or using if
statements:
func check2(f *Foo) error {
if n(f.Bar) {
return errors.New("Missing 'bar'")
}
if n(f.Qux) {
return errors.New("Missing 'qux'")
}
if n(f.Baz) {
x := int64(42)
f.Baz = &x
}
return nil
}
Try these on the Go Playground.