2 ms·
You could bind the variable each time, if that is allowed: err := DoFoo(); if err != nil ... err := DoBar() if err != nil ... DoFoo and DoBar are dif
by kazinator 3y ago
You could bind the variable each time, if that is allowed:
err := DoFoo();
if err != nil ...
err := DoBar()
if err != nil ...
DoFoo and DoBar are different functions; their error return might not even be the same type.
If mixed declarations and statements are not supported:
{
err := DoFoo();
if err != nil ...
}
{
err := DoBar()
if err != nil ...
}
this is what I do in C to reduce the scope of variables, and it has the benefit over
the former example in that we delimit where the scope begins and ends. We know that
after the closing brace, nothing can be referencing that err variable.
(I'm not a fan of mixed decls and statements).
Modern languages should support binding a variable in if:
if (err := DoFoo()) {
// err scoped here
}
My first example would be "bad" according to David Betz because it perpetrates shadowing.