Golang: using pointers in for-range loop

You can achieve the same effect without a function though: just create a local copy and use the address of that:

for _, each := range arr {
    each2 := each
    err := ds.repo.Insert(&each2)
    // ...

Also note that you may also store the address of the slice elements:

for i := range arr {
    err := ds.repo.Insert(&arr[i])
    // ...

Solve “using a reference for the variable on range scope `xxxx` (scopelint)” error.

Categories: Go

You may also like


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *