循环添加条目到地图

I am trying to implement in my application a way to separate users per country and then, send them to different actions.

This is what I have right now:

var manyUsers zendesk.ManyUsers
users := make(map[string]zendesk.ManyUsers)

for {
    ...
    manyUsers.AppendUsers(mysqlRequest(country, id))
    users[country] = manyUsers

    fmt.Printf("[%s]: %#v

", country, users[country])
}

But I figure out that after when I add a 3 different countries, it will generate 3 diferent keys, but the last one will have the 3 users from the other countries.

This is my AppendUsers function

func (users *ManyUsers) AppendUsers(user User) []User {
    users.Users = append(users.Users, user)

    return users.Users
}

I would like to thanks @kostix and @cloudaice for the answers.

I figure out what I need to do, I used what @kostix suggested, so I create in each iteration in my for loop, the var manyUsers zendesk.ManyUsers but I also added the follow:

manyUsers = users[country]
manyUsers.AppendUsers(mysqlRequest(country, id))
users[country] = manyUsers

Passing the current value from each country to my manyUsers I am capable of add a new User element in the ManyUsers struct and return the appended value to the users[country]. So, I never aggregate data from iteration and each country gets the correct amount of users.

Thank you.

the type of manyUsers is value not reference,so the follow code maybe ok

var manyUsers *zendesk.ManyUsers
users := make(map[string]*zendesk.ManyUsers)
......

You essentially modifying the same variable manyUsers on each iteration of your for loop and use that single instance as the value each time you create the new map entry.

You did not show us how your zendesk.ManyUser is defined but if it has reference semantics all your map entries will share the same data.

My guess (given the incomplete problem statement) is that you need to create a new instance of zendesk.ManyUser on each iteraition of your loop:

users := make(map[string]zendesk.ManyUsers)

for {
    ...
    var manyUsers zendesk.ManyUsers
    manyUsers.AppendUsers(mysqlRequest(country, id))
    users[country] = manyUsers

    fmt.Printf("[%s]: %#v

", country, users[country])
}

A no-brainer demonstration of the effect is there — observe that the iterations of the first loop modify the same variable while in the second loop each iteration first gets a fresh instance of a variable.