Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the shorthand of declaration & initialization are evaluated in go lang?

Tags:

go

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)

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

  2. 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.

  • a,b = b, a+b
  • a=b, b=a+b

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?

like image 367
Amol M Kulkarni Avatar asked Apr 06 '15 11:04

Amol M Kulkarni


People also ask

How do you write the short form of register?

reg | Business Englishreg. written abbreviation for registration : I needed to know the reg. number of the car.

How do you write International in short form?

The most common abbreviations for international are, Int. Intl. Int'l.

How do you abbreviate preamble?

Preamble is abbreviated pmbl. (as in my opening quotation).


1 Answers

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

like image 136
IamNaN Avatar answered Nov 02 '22 06:11

IamNaN