strings.Builder
iteration variables in traditional 3-clause for;;
loops are implemented incorrectly
for
loops, including both for-range
loops and traditional 3-clause for ..; ..; .. {...}
loops. For details, please read for
Loop Semantic Changes in Go 1.22: Be Aware of the Impact.
for-range
loops is positive, while the overall impact of the new semantics of traditional 3-clause for;;
loops is negative. The above referenced article shows the all the bad effects of the semantic change of traditional 3-clause for;;
loops I have found so far.
strings.Builder
values are used as (freshly-declared) iteration variables of traditional 3-clause for;;
loops. The following example shows one such case:
package main
import (
"fmt"
"strings"
)
func foo() string {
for b, i := (strings.Builder{}), byte('a'); ; i++ {
b.WriteByte(i) // not panic
if i == 'z' {
return b.String()
}
}
}
func bar(callback func(*strings.Builder)) string {
for b, i := (strings.Builder{}), byte('a'); ; i++ {
b.WriteByte(i) // panics here
callback(&b)
if i == 'z' {
return b.String()
}
}
}
func main() {
fmt.Println(foo())
debugProcess := func(pb *strings.Builder) {
//fmt.Println(pb.String()) // do nothing
}
fmt.Println(bar(debugProcess))
}
$ gotv 1.21 run main.go [Run]: $HOME/.cache/gotv/tag_go1.21.12/bin/go run main.go abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz
$ gotv 1.22 run main.go [Run]: $HOME/.cache/gotv/tag_go1.22.5/bin/go run main.go abcdefghijklmnopqrstuvwxyz panic: strings: illegal use of non-zero Builder copied by value
foo
and bar
functions should be consistent with each other, but official Go toolchain v1.22+ fail to make the guarantee. In fact, by the Go 1.22+ new semantics, both of the foo
and bar
functions should produce a panic, because nocopy values should not be used as (freshly declared) iteration variables since Go 1.22.
go vet
command provided in Go toolchain 1.22 and 1.23 versions failed to warn on such cases.
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.