Three new books, Go Optimizations 101, Go Details & Tips 101 and Go Generics 101 are published now. It is most cost-effective to buy all of them through this book bundle in the Leanpub book store.

A channel comparison bug when channels are used as case expressions of switch code blocks (in Go toolchain v1.20 - v1.23.x)

(The releatd issue: https://github.com/golang/go/issues/67190.)

In Go toolchain v1.20 - v1.23.x, there is a channel value comparison bug, which is demonstrated in the following program:

package main

import "fmt"

func main() {
	x := make(chan struct{})

	var y <-chan struct{} = x

	switch x {
	case y: fmt.Print(1)
	default: fmt.Print(0)
	}

	switch y {
	case x: fmt.Print(1)
	default: fmt.Print(0)
	}

	fmt.Println(x == y)
}

The program should print 11true. But it prints 01true with Go toolchain versions from v1.20 to v1.23.x.

$ gotv 1.19. run aa.go
[Run]: $HOME/.cache/gotv/tag_go1.19.13/bin/go run example.go
11true
$ gotv 1.20 run aa.go
[Run]: $HOME/.cache/gotv/tag_go1.20/bin/go run example.go
01true
$ gotv 1.21. run aa.go
[Run]: $HOME/.cache/gotv/tag_go1.21.12/bin/go run example.go
01true
$ gotv 1.22. run aa.go
[Run]: $HOME/.cache/gotv/tag_go1.22.5/bin/go run example.go
01true
$ gotv 1.23. run aa.go
[Run]: $HOME/.cache/gotv/tag_go1.23rc1/bin/go run example.go
01true
$ gotv :tip run aa.go
[Run]: $HOME/.cache/gotv/bra_master/bin/go run example.go
11true

The bug started from Go toolchain version v1.20 and has been fixed since v1.24.

If you are using a Go toolchain version between v1.20 and v1.23.x, you should be aware of this bug.

(GoTV is a tool used to manage and use multiple coexisting installations of official Go toolchain versions harmoniously and conveniently.)


(more articles ↡)

The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.

Tapir, the author of Go 101, has been on writing the Go 101 series books and maintaining the go101.org website since 2016 July. New contents will be continually added to the book and the website from time to time. Tapir is also an indie game developer. You can also support Go 101 by playing Tapir's games (made for both Android and iPhone/iPad):
Individual donations via PayPal are also welcome.

Articles in this book: