Ghost
Ghost

Reputation: 569

In goLang why are we creating the channel inside a for loop each time

I am trying to learn goLang by studying different examples online. in this one example it is a quiz test where a CSV file is given to the user with questions and answers, the timer fires if the user does not answer the Q in a given time. What I don’t understand in the code below why are we creating the answer channel in for loop each time for every different question. why can’t we define the timer outside the for loop and use that for every question isn’t that inefficient coding?

problemloop:
    for i, p := range problems {
        fmt.Printf("Problem #%d: %s = ", i+1, p.q)
        answerCh := make(chan string)
        go func() {
            var answer string
            fmt.Scanf("%s\n", &answer)
            answerCh <- answer
        }()

        select {
        case <-timer.C:
            fmt.Println()
            break problemloop
        case answer := <-answerCh:
            if answer == p.a {
                correct++
            }
        }
    }

Upvotes: 1

Views: 862

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273496

In Go, creating channels is very cheap. It's a common idiom, therefore, to create an "answer channel" you pass to a goroutine. Goroutines can't just return a value to a caller the way a function can do. When the goroutine is done, it sends its answer/result to the channel. Receiving on this channel in the main (or some other consumer) goroutine serves as a sync point. And allows to do timeouts, like your example demonstrates.

I wouldn't worry about efficiency here unless you can prove with profiling that this is the hot path. It's likely that this code could have been written with a single channel, but it's hard to say looking at the small snippet you provided.

Upvotes: 2

Related Questions