heretoinfinity
heretoinfinity

Reputation: 1746

Clarification on Go channels tutorial from some missing word or words

This page on a Go Tutorial about channels seems to be missing a word(s) or was just not edited. I can't tell what it is supposed to say about sending and receiving through channels.

By default, sends and receives block until the other side is ready.

Is a block something within Go? I haven't seen it before. Is block being used as a noun?

I tried searching for clarification. The only other page that has similar wording is educative.io

Moreover, by default, channels send and receive until the other side is ready

But it doesn't make sense. Do they mean:

Upvotes: 0

Views: 46

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213608

"Block" means that the goroutine will wait. You could write it this way:

By default, sends and receives wait until the other side is ready.

"Block" is just the normal term for this. It is not specific to Go. It is possible to use a channel in Go in a non-blocking manner:

  1. You can create a channel with a buffer. As long as there is space in the buffer, a write is non-blocking (but it will block if the buffer is full). As long as there is data in the buffer, a read is non-blocking (but it will block if the buffer is empty).

  2. You can use a select statement with a default branch.

var readch chan int
var writech chan int
var value int
select {
case n := <- readch:
    // Received data.
case writech <- value:
    // Sent data.
default:
    // Didn't send or receive data.
}

In this code, instead of blocking (waiting), the goroutine will go to the default branch.

Upvotes: 2

Related Questions