Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Simultaneous Assignment |
| 2 | |
| 3 | Simultaneous assignment is useful in many cases to make related assignments in a single statement. Sometimes they are required, either because only a single statement is available (e.g. in an if statement) or because the values will change after the statement (e.g. in the case of swap). All values on the right-hand side of the assignment operator are evaluated before the assignment is performed. |
| 4 | |
| 5 | Simultaneous assignment in an if statement can improve readability, especially in test functions: |
| 6 | ``` |
| 7 | if got, want := someFunction(...), currTest.Expected; got != want { |
| 8 | t.Errorf("%d. someFunction(...) = %v, want %v", currIdx, got, want) |
| 9 | } |
| 10 | ``` |
| 11 | |
| 12 | Swapping two values is also made simple using simultaneous assignment: |
| 13 | |
| 14 | ``` |
| 15 | i, j = j, i |
| 16 | ``` |
| 17 | |
| 18 | http://golang.org/ref/spec#Assignments |