What's the best / standard way to iterate results from a function call where it returns the tuple (result, err)
.
Example :
func getSlice() ([]string, error) {
return []string{"a", "b", "c"}, nil
}
for _, letter := range getSlice() {} //how should it be done here?
Is that even a good thing to consider?
If a function returns an error too, you should always check that first, and only proceed to use other results if the returned error allows so (most often if it's equal to nil
).
So do it like this:
s, err := getSlice()
if err != nil {
// Handle error and optionally return
log.Printf("getSlice error: %v", err)
return
}
for _, letter := range s {
// Use letter
}
If you don't need to return in case of errors, and you only need to use the result once, you may also do it like this:
if s, err := getSlice(); err == nil {
for _, letter := range s {
// Use letter
}
} else {
log.Printf("getSlice error: %v", err)
}