I have two structures that are similar and I want to assign one to the other. The first one "Equipment" is the structure used to match the database. The second one "JsonEquipment" is the helper structure to parse JSON data.
Here is the example:
type Equipment struct {
ID uint
CategoryID uint
Ip string
Login string
Password string
}
type JsonEquipment struct {
ID *uint
Category *string
Ip *string
Login *string
Password *string
}
The pointers are there to check if the field is present or not in the JSON. More info: How to recognize void value and unspecified field when unmarshaling in Go?
So for the moment I created a function with many "if" to check and assign to the Equipment but I wonder if there is a better & cleaner solution.
func CreateEquipment(item JsonEquipment) (Equipment) {
e := Equipment{}
if item.ID != nil && !previousEquipment.Auto { // Is the field present & not automatic equipment
e.ID = *item.ID
}
if item.Ip != nil { // Is the field present ?
e.Ip = *item.Ip
}
if item.Login != nil { // Is the field present ?
e.Login = *item.Login
}
[...]
return e
}
I hope you grasp the idea.
This question is similar to Assign struct with another struct but is different because of the pointers => non pointers struct