-1

I have a piece of code:

    //initialize a slice
    arr := make([]int, 0)
    arr = append(arr, 1, 2)
    for _, k := range arr {
        fmt.Printf("%p  %+v\n", &k, k)
    }

    //make a copy, but the element is a pointer
    arrP := make([]*int, 0)
    for _, k := range arr {
        arrP = append(arrP, &k)
    }
    //why arrP is different with arr?
    for _, k := range arrP {
        fmt.Printf("%p  %+v\n", k, *k)
    }

the results are : 0xc000018088 1 0xc000018088 2 0xc000090000 2 0xc000090000 2 my questions:
why address is the same?
why the value of arrP[0] is not 1?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
chaos
  • 133
  • 5
  • 2
    The expression `&k` is the address of the variable `k`, not the slice element. Use `&arr[i]` to get the address of the slice element. – Charlie Tumahai Feb 24 '20 at 04:07
  • 1
    Possible duplicate of [1](https://stackoverflow.com/questions/46169351/how-to-explain-golang-slice-ranges-phenomenon), [2](https://stackoverflow.com/questions/48826460/using-pointers-in-a-for-loop-golang), [3](https://stackoverflow.com/questions/56944781/why-is-string-pointer-in-golang-behavior-counter-intuitive-in-range-loop), [4](https://stackoverflow.com/questions/32401933/go-loop-pointer-changes), ... – Charlie Tumahai Feb 24 '20 at 04:53

1 Answers1

2

See Go CommonMistakes: Using reference to loop iterator variable

why address is the same?

The value of k is updated as the loop advances forward.

why the value of arrP[0] is not 1?

Same as the above.

To demonstrate with a modified-version of the example that you provided:

    arr := make([]int, 0)
    arr = append(arr, 1, 2)
    for i, _ := range arr {
        fmt.Printf("%p  %+v\n", &arr[i], arr[i])
    }

    arrP := make([]*int, 0)
    for i, _ := range arr {
        arrP = append(arrP, &arr[i])
    }

    for i, _ := range arrP {
        fmt.Printf("%p  %+v\n", arrP[i], *arrP[i])
    }

Results are:

0xc00009a010  1
0xc00009a018  2
0xc00009a010  1
0xc00009a018  2
Shang Jian Ding
  • 1,931
  • 11
  • 24
  • 1
    Code in your answer returns the same results as OP's. Are you sure you did not post the same original piece of code? – zerkms Feb 24 '20 at 04:49