更改结构值

Playing with golang and don't understand why can't I change user's email inside userGroup struct.

package main

import "fmt"

type user struct {
    name, email string
}

func (u *user) changeEmail(newEmail string) {
    u.email = newEmail
}

type userGroup struct {
    users map[int]user
}

func (ug *userGroup) mapOverUsers(fn func(u *user)) {
    usersLen := len(ug.users)
    for i := 0; i < usersLen; i++ {
        usr := ug.users[i]
        fn(&usr)
    }
}

func main() {
    ug := userGroup{
        map[int]user{0: {"0", "ZZZ"}, 1: {"1", "ZZZ"}, 2: {"2", "ZZZ"}}}

    fmt.Println(ug)

    // should be same as (&ug).mapOverUsers
    ug.mapOverUsers(func(u *user) {
        u.changeEmail("XXX")
        fmt.Println(u)
    })

    fmt.Println(ug)
}

I checked, and I believe I reference same addresses in memory for ug (userGroup) and u (user). Maybe it's not right approach, just reading a book on go and trying simple thing as I go. Thank you.

The line

usr := ug.users[i]

creates a copy of the user in the map. This copy is modified. There are two ways to fix this. The first is store a pointer to a user in the map:

type userGroup struct {
    users map[int]*user
}

playground example

The second is to store the value back the map after modification:

    usr := ug.users[i]
    fn(&usr)
    ug.users[i] = usr

playground example