Assigned pointer field becomes

前端 未结 1 394
暖寄归人
暖寄归人 2021-01-15 01:47

I have a struct:

type user struct {
Id string
..
data_ptr *userData
}

And I store slice of users in global scope:

type Hall         


        
1条回答
  •  礼貌的吻别
    2021-01-15 02:26

    This is because you operate on a copy and not on the slice element itself.

    In your haveUserId() function the for ... range makes a copy of the elements it loops over, and you return the address of this copy. And so later you will modify this copy which is independent from the value in the slice. So if later you check the address in the slice element, it will still be unchanged (nil).

    Possible fix: return the address of the slice element: &h.users[i]

    func (h *Hall) haveUserId(id string) (bool, *user) {
        for i := range h.users {
            if h.users[i].Id == id {
                fmt.Println("UID found")
                return true, &h.users[i]
            }
        }
        return false, nil
    }
    

    To demonstrate this, see this example:

    type Point struct{ x, y int }
    ps := []Point{{1, 2}, {3, 4}}
    fmt.Println(ps) // Output: [{1 2} {3 4}]
    
    for _, v := range ps {
        v.x += 10 // Modifies just the copy
    }
    fmt.Println(ps) // Output (unchanged): [{1 2} {3 4}]
    
    for i := range ps {
        ps[i].x += 10 // Modifies value in slice
    }
    fmt.Println(ps) // Output (changed): [{11 2} {13 4}]
    

    Try it on the Go Playground.

    0 讨论(0)
提交回复
热议问题