I have a struct which represents an object in a database, something like:
type Object struct {
Id string
Field1 string
Field2 int
}
And I’d like to have a function that updates the specific field in the database whenever the field is modified, something along these lines:
func (self *Object) SetField1(value string) {
self.Field1 = value
database.Update(self.Id, "Field1", self.Field1) // pseudocode
}
Is there a way to replace the "Field1" hard-coded string such that my code is resistant to future changes in the struct field ordering and naming?
I’ve poked around the reflect package, and it would be nice to be able to get the StructField that represents the field I’m working with, but it seems to require either the name of the field via hard-coded string, or the field’s index in the struct (which is subject to change).
You could validate your string by adding a method something like this:
And then use it when passing the string to the database update
But I would think that if you’re willing to use reflection, that you’d be better off just making a generic
setFieldmethod that accepts the field as a string, and the value as ainterface{}, checks the field and value, sets the value and updates the database.This way everything is done using the string, so it’ll either work or panic, and you don’t need to remember to use the
.verify()method.Somthing like:
Though I don’t think this’ll work on unexported fields.