The Go Optimizations 101, Go Details & Tips 101 and Go Generics 101 books are all updated to Go 1.25. The most cost-effective way to get them is through this book bundle in the Leanpub book store.

If you would like to learn some Go details and facts every serveral days, please follow @zigo_101.

The go 1.mn directive line in go.mod file doesn't work with some Go toolchain versions for some Go source files which contain //line ... comment directives

Go 1.22 changed the semantics of for-range and traditional for;; loops. Because the semantic changes alter the behavior of existing code written according to the previous semantics, they break backward compatibility.

While the behaviors of old for-range loops are almost unaffected, some old traditional for;; loops exhibit unexpected behaviors due to the breakage.

To prevent legacy code from malfunctioning, Go 1.22 and later requires that every Go source file must be specified with a Go version. There are two common ways to do this.

The first way is to add a //go:build go1.mn comment at the very beginning of a Go source file. However, certain versions of the Go toolchain are known to have bugs when handling this directive.

The other way is to add a go 1.mn directive in the go.mod file of the containing module of a Go source file. Unfortunately, some versions of the Go toolchain also contain bugs in how they process this.

For example, consider a module where the go.mod file specifies version 1.21. If that module is compiled using Go toolchain 1.22.x or 1.23.y, the program will print 210 (the new behavior) instead of the expected 333 (the old behavior). This demonstrates that the toolchain is failing to respect the version specified in the go.mod file.

go.mod
module main

go 1.21

main.go
//line main.go:1
package main

func main() {
	for i := 0; i < 3; i++ {
	    defer func() {
	        print(i)
	    }()
	}
}

The bug, tracked in https://github.com/golang/go/issues/77248, was identified as Go 1.26 approached release. Consequently, the following Go toolchain versions are permanently affected by this bug:


(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.

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

Articles in this book: