Sobes.tech
Junior — Senior

Features of using pointers inside a range loop

livecode

Task condition

Question: What numbers will be printed if references to the iterator variable inside the range loop are stored, and why might the output differ from what is expected?

package main

import (
    "fmt"
)

func main() {
    var ptrs []*int               // slice of pointers
    for _, v := range []int{10, 20, 30, 40} {
        ptrs = append(ptrs, &v)   // store the address of the iterator variable
    }

    for _, p := range ptrs {
        fmt.Printf("%d ", *p)   // print the value pointed to by each pointer
    }
}