doutao6380 2013-01-25 02:18
浏览 23
已采纳

获取已知结构字段的名称

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

  • 写回答

2条回答 默认 最新

  • dsgsgs30201 2013-01-25 15:00
    关注

    You could validate your string by adding a method something like this:

    func (self *Object) verify(field string) string {
        if _, ok := reflect.TypeOf(*self).FieldByName(field); ok {
            return field
        }
        panic("Invalid field name")
    }
    

    And then use it when passing the string to the database update

    func (self *Object) SetField1(value string) {
        self.Field1 = value
        database.Update(self.Id, self.verify("Field1"), self.Field1) // pseudocode
    }
    

    But I would think that if you're willing to use reflection, that you'd be better off just making a generic setField method that accepts the field as a string, and the value as a interface{}, 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:

    func (self *Object) SetField(field string, value interface{}) {
        // verify field and value using reflection
        // set the value using reflection
        database.Update(self.Id, field, self.Field1)
    
    }
    

    Though I don't think this'll work on unexported fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法