go - Returning an optional value and an error -
what's best signature function returns optional value , possible error?
for example:
func findcolor(name string) (rgb, error) { ... }
(the empty rgb value black, valid color, can't utilize infer no value found. assume error might come database connection.)
the 2 options seem best boolean homecoming value:
func findcolor(name string) (rgb, bool, error) { ... } c, ok, err := findcolor(myname) if !ok { ... } else if err != nil { ... } ...
or special error value:
var colornotfound = errors.new(...) func findcolor(name string) (rgb, error) { ... } c, err := findcolor(...) if err == colornotfound { ... } else if err != nil { ... } ...
(making special errors seems pain.)
what's idiomatic approach?
the convention in go homecoming (value, error)
, if error != nil
value
(or may be) invalid.
if have special errors need (like io.eof) making specific error normal practice. 3rd illustration idiomatic, if want different colornotfound
.
var colornotfound = errors.new(...) func findcolor(name string) (rgb, error) { // ... } c, err := findcolor(...) if err == colornotfound { // special if colornotfound... } else if err != nil { // other kind of error... }
go
No comments:
Post a Comment