The shorthand for declaration and initialization in go is
var a, b, c = 1 , 2, 3
Equivalent to following way of declaration and initialization (as per specs)
a:=1 b:=2 c:=3
var a int var b int var c int a=1 b=2 c=3
But I am not getting the answer for the problem found in following code:
package main
import "fmt"
func main() {
var a int = 0
var b int = 1
fmt.Println("init a ",a)
fmt.Println("init b ",b)
a, b = b, a+b
fmt.Println("printing a after `a, b = b, a+b`",a)
fmt.Println("printing b after `a, b = b, a+b`",b)
}
Output should be:
printing a after 'a, b = b, a+b' 1
printing b after 'a, b = b, a+b' 2
Since the value of b
is evaluated with a + b
i.e 1+1
= 2. But its giving 1.
Here is the playground links of both the working code where you can observe the difference.
I know I am missing something to understand, basically how the shorthand expression are evaluated especially when the same variable is involved in the expression.
But where is the proper documentation to refer. Could anyone help on this?
See here
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
Based on that a+b (0+1) is evaluated first. Then it's assigned. Thus you get the result of a = 1 and b = 1