Fix pointer is shared between loop iterations

Go pattern

$VALUE serves as a loop pointer that might be exported from the loop. Since this pointer is shared across loop iterations, the exported reference will consistently point to the last loop value, potentially leading to unintended consequences. To address this issue, duplicate the pointer within the loop to ensure each iteration has its own distinct reference.

references


Apply with the Grit CLI
grit apply exported_loop_pointer

loop iterations with pointers

BEFORE
func() {
    for _, val := range values {
        print_pointer(&val)
    }
}
AFTER
func() {
    for _, val := range values { 
        val := val 
 print_pointer(&val) 
    }
}

loop iterations with pointers under function

BEFORE
func() {
    values := []string{"a", "b", "c"}
    var funcs []func()
    for _, val := range values {
        funcs = append(funcs, func() {
            fmt.Println(&val)
        })
    }
}
AFTER
func() {
    values := []string{"a", "b", "c"}
    var funcs []func()
    for _, val := range values { 
        val := val 
 funcs = append(funcs, func() {
            fmt.Println(&val)
        }) 
    }
}

loop iterations with pointers and values assigned to new variable

GO
func() {
    values := []string{"a", "b", "c"}
    var funcs []func()
    for _, val := range values {
        val := val // pin!
        funcs = append(funcs, func() {
            fmt.Println(&val)
        })
    }
}

loop iterations without pointers

GO
func (){
	input := []string{"a", "b", "c"}
	output := []string{}
	for _, val := range input {
		output = append(output, val)
	}
}