Re:Much less than, Much greater than symbols
by Jtsummers on Sunday September 12, 2021 @01:32AM
(#28498827)
Golang uses := to represent declaration and simultaneous assignment to at least one new variable. = only works if the LHS variables have already been declared. If you use :=, at least one of the variables on the LHS has to be new. So the following snippet would be an error:
This is valid:
As is this:
And this is an error again:
Since neither a nor b are new variables.
[ Parent
| on HN ]
Re:Much less than, Much greater than symbols
by yissp on Sunday September 12, 2021 @07:52AM
(#28500337)
As someone who has never used go, the third example feels counter-intuitive to me. I would expect a, b := 4, 2; to be equivalent to a := 4; b := 2; is there a reason it was done this way?
Re:Much less than, Much greater than symbols
by jimktrains2 on Sunday September 12, 2021 @09:00AM
(#28500758)
It is as you say, however, a and b had already been declared, which is the error.
Re:Much less than, Much greater than symbols
by lostmsu on Sunday September 12, 2021 @02:10AM
(#28498974)
But... why the latter?
Re:Much less than, Much greater than symbols
by dasyatidprime on Sunday September 12, 2021 @02:37AM
(#28499083)
Because if you're modifying a function and you're adding a new variable to hold some intermediary value, you might accidentally pick a variable name that already exists. If you're in the habit of writing := to signal your intent to create a new variable, that error will probably get caught at compile time rather than being a source of subtle bugs where you trample data needed by something else.
The multi-variable case is trickier, especially because (result, err) is such a common pattern and you neither want to impede the very common case of storing a result into a new variable nor to require a profusion of differently-named variables for errors that are very likely to just get folded anyway. So it allows it if any of the variables are new rather than requiring all. But clearing a large chunk of the bug surface is still much better than not.
(This is only my extrapolated reasoning, of course.)