Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an optional value and an error

Tags:

go

What's the best signature for a function that returns an optional value and a possible error?

For example:

func findColor(name string) (RGB, error) {
    ...
}

(The empty RGB value is black, a valid color, so you can't use it to infer that no value was found. Assume the error might come from something like a database connection.)

The two options that seem best are a boolean return value:

func findColor(name string) (RGB, bool, error) {
    ...
}

c, ok, err := findColor(myname)

if !ok {
    ...
} else if err != nil {
    ...
}

...

Or a 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 like a pain.)

What's the most idiomatic approach?

like image 244
sleepytea Avatar asked Apr 18 '26 23:04

sleepytea


1 Answers

The convention in Go is to return (value, error) and if error != nil then value is (or may be) invalid.

If you have special errors you need to do something with (like io.EOF) then making a specific error is normal practice. So I would say your 3rd example is the most idiomatic, if you want to do something different for ColorNotFound.

var ColorNotFound = errors.New(...)

func findColor(name string) (RGB, error) {
    // ...
}

c, err := findColor(...)

if err == ColorNotFound {
    // Do something special if ColorNotFound...
} else if err != nil {
    // Some other kind of error...
}
like image 161
Nick Craig-Wood Avatar answered Apr 20 '26 12:04

Nick Craig-Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!