Hacker News new | ask | show | jobs
by nkozyra 4258 days ago
#3 has always bothered me. I feel like:

   someString := "hello"
   someString, err := ReturnStringAndError("world")
   if err != nil {
      fmt.Println("there's no way this could happen")
   } else {
      fmt.Println(someString)
   }
Should produce an error.
1 comments

It's a matter of pragmatism. When you have a sequence of functions that all return (res, err) pairs, it's extremely helpful to be able to use := even though the err is not redefined.

Occasionally, I wonder whether := with several variables on the left hand side should have been to defined to redefine variables (shadowing the earlier definition), but obviously the Go people thought that such shadowing would be worse.

Yup, this is why you don't need err1 err2 err3 err4... (I've had to do similar things in C# before).

Also, := does shadow in a sub-scope. The difference between shadowing and simply assigning in the same scope is negligible (i.e. either way you can't get at the old value).

    err := foo()
    if err != nil {
        err := bar() // err shadowed here
    }
    f, err := baz() // err assigned here
What would be the difference between shadowing and assigning on that last line? You can't unshadow without leaving scope, at which point the value you were shadowing also leaves scope.