go – chanA <- chanB : send and receive value or send channel itself?-ThrowExceptions

Exception or error:

It seems like the Go compiler will do two completely different semantic operations depending on the types in the following example:

chanA <- chanB

If chanA is type (chan chan<- string), this operation will send chanB, type (chan<- string), itself to chanA.

However, if chanA is type (chan<- string), it will try to extract a string from chanB, implying chanB’s type is (<-chan string).

Is the only way to reason about this to know the types, or is there an easy way to tell when a channel is sending values vs. itself?

I am looking at this example from the Go Programming Book: https://github.com/adonovan/gopl.io/blob/master/ch8/chat/chat.go

How to solve:

It’s very easy to tell.

chanA <- anything

is sending the value anything on chanA, no matter what anything is.

chanA <- <- chanB

is receiving a value from chanB and sending it on chanA.

Your second statement here:

However, if chanA is type (chan<- string), it will try to extract a string from chanB

is your issue. foo <- bar is always a send operation. The Go compiler reads from left to right, and identifier <- is a send operation.

A receive operation is an expression that evaluates to a value, so it can only be valid where a value would be valid – i.e., the compiler must have already encountered the first part of an assignment operation, send operation, function call, etc.

Answer´╝Ü

Your assumption is wrong.

chanA <- chanB

The above will only work if chanA is of type chan chan something. It will send chanB over chanA. It will not read from chanB.

To read a value from chanB and send it over chanA, you need:

chanA <- <- chanB

Leave a Reply

Your email address will not be published. Required fields are marked *