Why address of element in slice is the same? and how to copy them to a pointer?

Issue

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?

Solution

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

Answered By – Shangjian Ding

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.