登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-08 13:49:52 110浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何打印结构中结构切片的标签》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我有 struct config,它由字段 sliceofanotherstruct 组成,其中包含指向的指针切片 另一个结构

这里如何获取 anotherstruct 中 bank 字段的 json 标签。

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"`
}

解决方案


使用anotherstruct创建新变量,然后使用reflect尝试获取bank字段,之后就可以获得它的标签。

// 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
}

工作演示:https://play.golang.org/p/TJDCEVm23Hz

到这里,我们也就讲完了《如何打印结构中结构切片的标签》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>