3 ms·
var db *sql.DB var err error Why declare this error globally?
by insertnickname 10y ago
var db *sql.DB
var err error
Why declare this error globally?
- falcolas 10y agoThe DB: because there's an internal goroutine-safe connection pool, so you want it to either be global, or exist in the server singleton (i.e. global). The err: because they use it so frequently, easier to define it once and simply assign to it multiple times than try and track if it's already been defined per block of code. Personally, I prefer to use distinct error variables for each error which can be thrown, but either method is idiomatic.
- hellcow 10y agoIt's bad practice to define an error globally. Let's say you create a goroutine which uses that same err variable (such as an http handler)--now you have a race condition, as that memory is being modified across threads.
- falcolas 10y agoTrue, and looking at the code, it doesn't make sense to define it as a global, since each potential goroutine (i.e. the HTTP handler functions) is re-defining 'err' whenever it's being used.