I am quite familiar with pointers but I don’t get my current problem. Let’s take this example, I have a list of users and have to map them. firstName and lastName can be empty string and I need to return nil instead:
type OldUser struct {
ID int
FirstName string
LastName string
}
type User struct {
ID int
FirstName *string
LastName *string
}
users := make([]User, 0)
for _, u := range oldUsers {
var firstName *string
if u.FirstName != "" {
firstName = &u.FirstName
}
var lastName *string
if u.LastName != "" {
lastName = &u.LastName
}
users = append(users, User{
ID: u.ID,
FirstName: firstName,
LastName: lastName,
})
}
After the iteration all the new users have the firstName and lastName of the last mapped user. Why?
>Solution :
The for loop is iterating by value, copying each subsequent object from oldUsers into the loop variable u. So when taking the address of u.FirstName, all addresses end up the same.
You can fix this by creating a copy of u at the start of the loop, using the odd-looking statement:
var u = u