Channel receive operator. Untyped boolean result.

77 views
Skip to first unread message

Laevus Dexter

unread,
Jun 21, 2020, 5:10:46 PM6/21/20
to golang-nuts

A receive expression used in an assignment or initialization of the special form

x, ok = <-ch
x, ok := <-ch
var x, ok = <-ch
var x, ok T = <-ch

yields an additional untyped boolean result reporting whether the communication succeeded. The value of ok is true if the value received was delivered by a successful send operation to the channel, or false if it is a zero value generated because the channel is closed and empty.


Why it's untyped? And how to make the last expression to work? Seems I can't use anything but bool. 

Ian Lance Taylor

unread,
Jun 21, 2020, 11:15:13 PM6/21/20
to Laevus Dexter, golang-nuts
It's untyped mainly because there is no reason to make it typed.

You can use a different type by writing code like (untested):

type MyBool bool

func F(c chan int) {
var (
x int
ok MyBool
)
x, ok = <-c
}

Ian

Laevus Dexter

unread,
Jun 22, 2020, 3:38:15 PM6/22/20
to golang-nuts
I get it, thanks.
Reply all
Reply to author
Forward
0 new messages