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.
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