I have some Go code that queries a Database using the "database/sql" package. Most of these functions return: result, err
or rows, err
.
Because of this, you end up with many repetitive blocks like this:
if err != nil {
// Handle Error
}
I've seen "cleaner" code for functions that only return err:
if err := SomeFunc(); err != nil {
// Handle Error
}
I can't do this with these functions because the variable gets trapped in the scope when I need to access it in another query function later on.
Is there a way to clean up this go code?
They're only trapped in scope if they're declared in the if
block using :=
. If you declare them outside the if
, they're in the outer scope:
var err error
var result SomeResultType
if result,err = SomeFunc(); err != nil {
// Handle error
}
// Do something with result (or error if you want)