0

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?

2
  • Tangential: if you use sqlx, you can use Get() and Select() to pull, respectively, a single entry or a slice of entries without having to handle a rows variable. Those functions return only an error, and thus work well with the if <statement>; <conditional> { style. sqlx is also just a really amazing library in general. Commented Apr 23, 2018 at 20:34
  • Possible duplicate of Handling multiple errors in go Commented Apr 24, 2018 at 7:31

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Though in this case, simply moving the function call outside the if statement (and using shortform declaration) is actually a more compact code style. Declaring the vars beforehand added 2 lines when moving the statement into the if block saved 1 line. Can work rather well if the vars are already declared for some reason or if you use named returns, though.
Either way, it has the same effect of moving the declaration outside the block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.