The problem that I am facing is more of a code design rather than specifically go related. I am building a simple CRUD application and everything seems to go nice and easy except the updating part: I have a struct type as simple as:
type User struct {
ID string
Name string
Password string
}
and an interface for data storage layer:
type Store interface {
...
Update(user *User) error
...
}
The problem is that with most database drivers you can't just pass the whole struct instance and hope the their system knows which fields were modified, the whole document/row gets replaced. How should I track which fields were modified (so that I could update them in the storage layer accordingly)? Maybe pass all the fields I would like to modify to the Update function as a map of interface{}?
There are plenty of ways to achieve that. For example you can use setters to change the values.So you can keep track of updated fields. like so :
type User struct {
ID string
Name string
Password string
updateFields map[string]bool
}
func (u *User) SetName(name string) {
u.Name = name
updateFields["name"] = true
}
You can use more automated way by reflection.