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:

// chan-cmp-bug.go
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.0 (exclusive).

$ gotv 1.19. run chan-cmp-bug.go
[Run]: $HOME/.cache/gotv/tag_go1.19.13/bin/go run chan-cmp-bug.go
11true
$ gotv 1.20 run chan-cmp-bug.go
[Run]: $HOME/.cache/gotv/tag_go1.20/bin/go run chan-cmp-bug.go
01true
$ gotv 1.21. run chan-cmp-bug.go
[Run]: $HOME/.cache/gotv/tag_go1.21.12/bin/go run chan-cmp-bug.go
01true
$ gotv 1.22. run chan-cmp-bug.go
[Run]: $HOME/.cache/gotv/tag_go1.22.5/bin/go run chan-cmp-bug.go
01true
$ gotv 1.23.0 run chan-cmp-bug.go
[Run]: $HOME/.cache/gotv/tag_go1.23rc1/bin/go run chan-cmp-bug.go
11true

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

If you are using a Go toolchain version between v1.20 and v1.23.0 (exclusive), 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.)


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.