gostructtypesvariable-assignmentmass-assignment

Is it possible to use mass assignment in golang?


I have my struct like this:

type User struct {
    Id uint64
    Email string
}

And I know, that I can declare it like this:

user := User{
    Id: 1,
    Email: "test@example.com",
}

And I can update it like this:

user.Id = 2
user.Email = "test1@example.com"

Is it possible to use similar construction like for creating but for updating struct?


Solution

  • No, there really isn't an equivalent multi-property setter.

    EDIT:

    Possibly with reflection you could do something like:

    updates := user := User{
      Email: "newemail@example.com",
    }
    //via reflection (pseudo code)
    for each field in target object {
      if updates.field is not zero value{
         set target.field = updates.field
      }
    }
    

    The reflection part could be factored into a function updateFields(dst, src interface{}), but I would generally say the complexity is not worth the savings. Just have a few lines of setting fields one by one.