[golang] for ... range指针的坑

话不多说,看代码知道输出结果么?

import (
    "github.com/spotmaxtech/gokit"
    "testing"
)

func TestRangeFault(t *testing.T) {
    l1 := []int{1,2,3,4,5}
    var l2 []*int
    for _, i := range l1 {
        l2 = append(l2, &i)
    }

    t.Log(gokit.Prettify(l2))
}

输出结果

=== RUN   TestRangeFault
--- PASS: TestRangeFault (0.00s)
    lesson18-_test.go:67: [
          5,
          5,
          5,
          5,
          5
        ]
PASS

Process finished with exit code 0

for range每次循环使用的是同一个临时变量!每次都是做了一次值拷贝而已,引用它的指针是有问题的!

你可能感兴趣的:([golang] for ... range指针的坑)