3 ms·
The article has two examples of how I already find Go to be inconsistent and/or surprising: w, err := b.NewWriter(ctx, "gopher.png", nil) ... _, er
by sbjs 8y ago
The article has two examples of how I already find Go to be inconsistent and/or surprising:
w, err := b.NewWriter(ctx, "gopher.png", nil)
...
_, err = w.Write(data)
...
if err := w.Close(); err != nil
Why is := used on the first line but = used on the second line, and then := used again on the third line? I get that you use := when introducing a new variable, and = when just assigning, the third line is not really introducing a new variable, since err is still in scope... or is it?
Not to mention, what is the last argument `nil` supposed to represent? In most high quality Node.js libraries, functions/constructors will take an optional options object so you can omit it, or pass an object like { timeout: 300 } to it.
- elithrar 8y ago> the third line is not really introducing a new variable, since err is still in scope... or is it? The "if" block creates a new scope.
- skj 8y agoThe third line has a new err inside the if statement's scope. It's equivalent to { // begin new scope here err := w.Close() if err != nil { foo } else { bar } }
- deleted 8y ago[deleted]
- ssambros 8y agoThird line ':=' is not required, you can reuse globally scoped 'err' with '=' as well; unless you want to preserve the current value of global 'err' for future use (which would be confusing).
- ironjunkie 8y agoagreed that the := that can be used when one new var is introduced but not the others is extremely confusing. I also hate the inconsistent behavior when you check multiple errors in a row, the first one will get := but not the second one (if you don't put those in a if statement, which I never do). But now if for some reason, you remove the first := statement, the code will error on the second one, that needs to be changed from = to :=