Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Side effect using pointers

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading