5 ms·
I mean, are we gonna talk about ‘=‘, ‘==‘, and ‘===‘?
by booleandilemma 5y ago
I mean, are we gonna talk about ‘=‘, ‘==‘, and ‘===‘?
- yjftsjthsd-h 5y agoDon't forget the languages that use := for assignment! And golang, which I vaguely think can use both = and := to do slightly different assignment (assignment vs initialization?).
- Jtsummers 5y agoGolang 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: a := 3 ... a := 4 This is valid: a := 3 ... a = 4 As is this: a := 3 ... a, b := 4, 2 And this is an error again: a := 3 b := 4 a, b := 1, 2 Since neither a nor b are new variables.
- lostmsu 5y agoBut... why the latter?
- dasyatidprime 5y agoBecause 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.)
- yissp 5y agoAs 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?
- jimktrains2 5y agoIt is as you say, however, a and b had already been declared, which is the error.
- marcosdumay 5y agoOh, this is a good time to remember Prolog exists. Assignment isn't even a concept there, but equality can act on so many different ways!