How is the transcript of declaration and initialization evaluated in go lang?

Shortcut for declaration and initialization in go

var a, b, c = 1 , 2, 3 

Equivalent to the following declaration and initialization method (as per specification )

  • a:=1 b:=2 c:=3

  • var a int var b int var c int a=1 b=2 c=3

But I do not get the answer to the problem found in the 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) } 

The conclusion 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 estimated using a + b ie 1+1 = 2. But its value is 1.

Here are links to playgrounds as a working code where you can watch the difference.

I know that I am missing something to understand, basically, how an expression of shorthand is evaluated, especially when the same variable is involved in the expression.

But where should the relevant documentation be. Can anyone help with this?

+6
source share
1 answer

Look here

The appointment continues in two stages. Firstly, expression index operands and pointers (including an implicit pointer pointers in selectors) on the left and expressions on the right are evaluated in the usual way. Secondly, tasks are performed in order from left to right.

Based on this, a + b (0 + 1) is first evaluated. Then he appointed. So you get the result a = 1 and b = 1

+6
source

Source: https://habr.com/ru/post/984739/


All Articles