Home > Back-end >  Go language simultaneous assignment through un-buffered channel: how does it work?
Go language simultaneous assignment through un-buffered channel: how does it work?

Time:11-25

I'm learning Go and saw this program at go.dev/tour/concurrency/2

package main

import "fmt"

func sum(s []int, c chan int) {
    sum := 0
    for _, v := range s {
        sum  = v
    }
    c <- sum // send sum to c
}

func main() {
    s := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    x, y := <-c, <-c // receive from c

    fmt.Println(x, y, x y)
}

I recall that in python the execution flow of a, b = b, a should be like:

  1. Create a temporary tuple of (b, a)
  1. Assign each value in (b, a) to variables in (a, b) with a loop

The method doesn't seem to apply to this occasion in GO. So what actually happens in that a, b = b, a sentence?

CodePudding user response:

a, b = b, a is an assignment, more specifically a tuple assignment.

It is detailed in the Spec: Assignments:

A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables.

[...] 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.

a, b = b, a  // exchange a and b

So first the (current) values of b and a are read, then they are assigned to a, b, effectively swapping their values.

This:

x, y := <-c, <-c

Is a short variable declaration, it is equivalent to a regular variable declaration with initializer expressions but no types:

var x, y = <-c, <-c

This will receive from c, twice, and assign the received values to x and y.

  •  Tags:  
  • go
  • Related