1
goofle
8y

Golang: It's stupid that the language doesn't allow the variable 'result' to be used out of the if scope, although it's been declared outside the if scope:
if result, err := foo(bar); err != nil {
// do something with err
}
// no err, so do something
// with result.
// But No! you can't.

Comments
  • 0
    @Letmecode Well to me the if-statement part is just the if err != nil part, and the short statement that precedes the actual condition, should be considered to be in the outer scope.
    Because I think the whole point of preceding if-statements with short statements is a way for writing fewer lines of code. Otherwise what's the point of doing them if I have to add another line of code to just declare the variable.
    I mean I could have write it this way from the beginning:
    result, err := foo(bar)
    if err != nil {
    // do something with err
    }
  • 0
    Readability > less lines. Your second example is easier to read, and I agree with @Letmecode that it totally makes sense that your first example doesnt work.
  • 0
    To me the two examples are no different. In both the variable 'result' has been declared and initialized _before_ the if clause, do you disagree with me about this fact?
    So as like any other variable in the outer scope, I think, it should, too, be avaible in the inner scope of the if-statement and also the scope it has been first declared or initialized.
Add Comment