duanke0555 2016-11-22 01:37
浏览 25
已采纳

如何标记无法修改的嵌入式结构的字段?

Suppose there is an external library libA who declares NotMyType.

type NotMyType struct {
  NotMyField string
}

And you would like to embed it with one of your own types, which you use with an ORM, which uses the tags to adjust column properties.

type MyType struct {
  SomeData0 string  `orm:"nullable"`
  SomeData1 string  `orm:"nullable"`
  libA.NotMyType
}

For example, columns MyType.SomeData0 and MyType.SomeData1 are NULLABLE.

Is it possible to tag NotMyField with orm:"nullable" without modifying NotMyType?

  • 写回答

2条回答 默认 最新

  • doutao5499 2016-11-22 02:01
    关注

    EDIT: wrong answer, my bad

    Okep i think i got it. I have never used reflect before so maybe i'm wrong. But :

    Take a look at what I just do :

    https://play.golang.org/p/U0uyomL-It

    I have a struct

    type User struct {
        name string
        age  int
    }
    

    With no tag.

    I get the field with

    field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
    if !ok {
        panic("Field not found")
    }
    

    And i set a new tag with

    //setStructTag(&field)
    
    func setStructTag(f *reflect.StructField) {
        f.Tag = "`json:name-field`"
    }
    

    Hope my researche will help you :)

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部