0

Is there an easy way to only update non-nil/empty fields in go(-lang)?

Given these two structs:

type UserAccount struct {
    Id         string `json:"id" binding:"required"`
    Enrolled   bool   `json:"enrolled" binding:"required"`
    Email      string `json:"email" binding:"required"`
    GivenName  string `json:"given_name" binding:"required"`
    FamilyName string `json:"family_name" binding:"required"`
    PictureURL string `json:"picture" binding:"required"`
    Nickname   string `json:"nickname" binding:"required"`
}
type ProfilePayload struct {
    Email      string `json:"email,omitempty"`
    GivenName  string `json:"given_name,omitempty"`
    FamilyName string `json:"family_name,omitempty"`
    PictureURL string `json:"picture,omitempty"`
    Nickname   string `json:"nickname,omitempty"` 
}

Is it possible to only update non-nil fields in an UserAccount struct. For example, all fields except Email are nil/empty in a ProfilePayload, is there an easy way to "merge" them together and only set the Email field in a UserAccount to a new value and keeping everything else in the UserAccount the same?

if payload.Email != "" {
    account.Email = payload.Email
}
....

Isn´t really an option for me.

3
  • 2
    Why is the conditional you mention not an option? Commented Apr 6, 2018 at 22:14
  • Because I want to do it with quite large structs and there has to be a better solution. Commented Apr 6, 2018 at 22:27
  • The only way to do it without explicitly checking every field is with reflection. See golang.org/pkg/reflect. Commented Apr 7, 2018 at 21:17

1 Answer 1

2

What if you just restructured your code

type ProfilePayload struct {
    Email      string `json:"email,omitempty"`
    GivenName  string `json:"given_name,omitempty"`
    FamilyName string `json:"family_name,omitempty"`
    PictureURL string `json:"picture,omitempty"`
    Nickname   string `json:"nickname,omitempty"` 
}
type UserAccount struct {
    Id         string `json:"id" binding:"required"`
    Enrolled   bool   `json:"enrolled" binding:"required"`
    ProfilePayload //now it has all the fields from ProfilePayload
}

When decoding to json you just decode it to UserAccount, and then you can extract ProfilePayload from UserAccount if you want

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.