ALL
Fix for-range Issue Again in Go 1.22
With the release of Go 1.22, the Go team addressed a long-standing issue with the for-range loop variable scoping, which had been a common pitfall for developers writing concurrent code. Specifically, the problem was that the loop variable in a for-range loop was reused across iterations, leading to unexpected behavior when closures were involved.The Issue Before Go 1.22Consider the following example:package forangeimport "fmt"func Do() { done := make(chan bool) values := []string{"a", "b", "c"} for _, v := range values { go func() { fmt.Println(v) // Prints unexpect...
Some tricks and tips for using for range in GoLang
GoLang provides two major ways to loop through elements of array, slice and map. They are for and for range. Many people find that for range is very convenient when don't care about the index of the element. In this post, some tricks and tips would be talked about regarding for range.1. Loop and get pointer of each elementAssume there is a code snippet like below which is to get the pointer of each element in an array and create a new array with the corresponding pointer.arr := [2]int{1, 2}res := []*int{}for _, v := range arr { res = append(res, &v)}//expect: 1 2fmt.Println(*res[0],*res...