dougao2830 2017-07-11 05:09
浏览 55

如何在Golang中实现导出字段的设置器?

I'm using gorm lib and to use that lib, I have to export all column fields. Something like this

type myType struct {
  Id int
  Name string
}

But with that, how to I deal with addition logics for struct fields. Let's say, what if I want to prefix Mr to the Name field? The client can always do myType.Name = "whatever". If I make Name to be unexported and have setter for it, that field will never work with gorm. Any golang-way to deal with this?

  • 写回答

1条回答 默认 最新

  • dongqiang5932 2017-07-11 05:43
    关注

    Your understanding is correct about unexported field with method.

    Your struct Fields have to be exported then only gorm will have access to it. That is Go way.

    So you have 2 options.

    Option 1: taking advantage of gorm callback AfterFind. Basically your struct have to implement this callback. After find you have to update the field Name.

    Option 2: Implement as part of your data fetch method. Update the field Name before returning to the caller.

    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)