dongwei3151 2018-10-31 05:49
浏览 47
已采纳

如何在结构中打印结构切片的标签

I have struct Config which consist of Field SliceOfAnotherStruct which contained the slice of pointer to AnotherStruct.

Here how could I get the json tag for field Bank in AnotherStruct.

type Config struct {
    SliceOfAnotherStruct         []*AnotherStruct        `bson:"anotherStruct" json:"anotherStruct" validate:"required,dive,required"`
}

type AnotherStruct struct {
    Name                   string        `bson:"name" json:"name" validate:"required"`
    Cost                   string        `bson:"cost" json:"cost" validate:"required"`
    Bank    string        `bson:"bank" json:"bank" validate:"required"`
    IFSC     string        `bson:"ifsc" json:"ifsc" validate:"required"`
}
  • 写回答

1条回答 默认 最新

  • duanhoupeng6642 2018-10-31 06:54
    关注

    Create new variable using AnotherStruct, then by using reflect try to get the Bank field, after that you'll be able to get it's tag.

    // new object created from struct AnotherStruct
    obj := AnotherStruct{}
    
    // getting `Bank` field information. 
    // the `FieldByName` function return two variables, 
    // 1. the field data 
    // 2. a boolean data, determines whether field is exists or not
    bankField, ok := reflect.TypeOf(obj).FieldByName("Bank")
    if ok {
        // if the field is exists, then get the desired tag
        jsonTagValue := bankField.Tag.Get("json")
        fmt.Println(jsonTagValue) // bank
    }
    

    Working playground: https://play.golang.org/p/TJDCEVm23Hz

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥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 基于单片机的靶位控制系统