Skip to content

Instantly share code, notes, and snippets.

@rousan
Last active June 4, 2018 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rousan/2aebab086677871740bf32689b20559a to your computer and use it in GitHub Desktop.
Save rousan/2aebab086677871740bf32689b20559a to your computer and use it in GitHub Desktop.
Evaluation order of assignment operator in GoLang

Evaluation order of assignment operator in GoLang

In GoLang, the evaluation order of assignment operator is straight forward.

The order is:

  1. Evaluate the lvalues to Memory Location from left to right.
  2. Evaluate the rvalues to constant values from left to right.
  3. And finallly, assign rvalues to lvalues from left to right.

The POC:

package main

import (
   "fmt"
)

func main() {
   arr := make([]int, 3)

   arr[echo(0)], arr[echo(1)], arr[echo(2)] = echo(3), arr[echo(0)]+echo(4), echo(5)
   fmt.Println(arr)
}

func echo(v int) int {
   fmt.Println(v)
   return v
}

The ouput:

0
1
2
3
0
4
5
[3 4 5]

Examples

swap.go

package main

import (
   "fmt"
)

func main() {
   a, b := 1, 2
   swap(&a, &b)
   fmt.Println(a, b)
}

func swap(a, b *int) {
   *a, *b = *b, *a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment