←back to thread

Go is still not good

(blog.habets.se)
644 points ustad | 2 comments | | HN request time: 0s | source
Show context
gwd ◴[] No.44983375[source]
Anyone want to try to explain what he's on about with the first example?

    bar, err := foo()
    if err != nil {
      return err
    }
    if err := foo2(); err != nil {
      return err
    }
The above (which declares a new value of err scoped to the second if statement) should compile right? What is it that he's complaining about?

EDIT: OK, I think I understand; there's no easy way to have `bar` be function-scoped and `err` be if-scoped.

I mean, I'm with him on the interfaces. But the "append" thing just seems like ranting to me. In his example, `a` is a local variable; why would assigning a local variable be expected to change the value in the caller? Would you expect the following to work?

    int func(a *MyStruct) {
      a = &MyStruct{...}
    }
If not why would you expect `a = apppend(a, ...)` to work?
replies(4): >>44983418 #>>44983426 #>>44983435 #>>44983907 #
1. terminalbraid ◴[] No.44983418[source]
You didn't copy the code correctly from the first example.
replies(1): >>44983478 #
2. gwd ◴[] No.44983478[source]
Well no, the second "if" statement is a red herring. Both of the following work:

    bar, err := foo()
    if err != nil {
      return err
    }
    if err = foo2(); err != nil {
      return err
    }
and

    bar, err := foo()
    if err != nil {
      return err
    }
    if err := foo2(); err != nil {
      return err
    }
He even says as much:

> Even if we change that to :=, we’re left to wonder why err is in scope for (potentially) the rest of the function. Why? Is it read later?

My initial reaction was: "The first `err` is function-scope because the programmer made it function-scope; he clearly knows you can make them local to the if, so what's he on about?`

It was only when I tried to rewrite the code to make the first `err` if-scope that I realized the problem I guess he has: OK, how do you make both `err` variable if-scope while making `bar` function-scope? You'd have to do something like this:

    var bar MyType
    if lbar, err := foo(); err != nil {
      return err
    } else {
      bar = lbar
    }
Which is a lot of cruft to add just to restrict the scope of `err`.