Why did I come across this Golang code?

I am new to Golang. I wrote the following code for practice and ran into a runtime error message:

package main

import (
    "fmt"
)

func system(WORKERS int) {
    fromW := make(chan bool)
    toW := make(chan bool)
    for i := 0; i != WORKERS; i++ {
        go worker(toW, fromW)
    }
    coordinator(WORKERS, fromW, toW)
}

func coordinator(WORKERS int, in, out chan bool) {
    result := true
    for i := 0; i != WORKERS; i++ {
        result =  result && <-in
    }
    for i := 0; i != WORKERS; i++ {
        out <- result
    }
    fmt.Println("%t", result)
}

func worker(in, out chan bool) {
    out <- false
    <-in
}

func main() {
    system(2)
}

However, if I replace the && operands on line 19 to

result =  <-in && result,

The code works correctly without returning any error messages. How can I explain this behavior? Did I miss something? The OS I use is Windows 10, and the Golang version is 1.8.3.

Thank you in advance.

+4
source share
1 answer

As you can see here , the right operand &&is evaluated conditionally.

, result = result && <-in <-in, result . , cudrinator false . &&, <-in , .

+6

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


All Articles