登录
首页 >  Golang >  Go问答

从Go结构中提取标签作为reflect.Value

来源:stackoverflow

时间:2024-04-28 20:36:35 447浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《从Go结构中提取标签作为reflect.Value》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在尝试从某个结构体值中提取标签。我能够获取结构的字段,但无法提取标签。我在这里做错了什么?我尝试了很多不同的方法(使用 reflect.type、interface{} 等),但都失败了。

type house struct {
    room string
    humans human
}

type human struct {
    name         string `anonymize:"true"` // unable to get this tag
    body         string
    tail         string `anonymize:"true"` // unable to get this tag
}

func printstructtags(f reflect.value) { // f is of struct type `human`
    for i := 0; i < f.numfield(); i++ {
        fmt.printf("tags are %s\n", reflect.typeof(f).field(i).tag) // tags aren't printed
    }
}

我使用 reflect.value 作为参数的原因是因为该函数是通过以下方式从另一个函数调用的

var payload interface{}
    payload = &House{}
    // Setup complete
    v := reflect.ValueOf(payload).Elem()
    for j := 0; j < v.NumField(); j++ { // Go through all fields of payload
        f := v.Field(j)
        if f.Kind().String() == "struct" { 
            printStructTags(f)
        }
    }

任何见解都非常有价值


正确答案


当你调用 reflect.typeof(f) 时,你会得到 f 的类型,它已经是 reflect.value 了。

使用此 ftype() 函数来获取类型并对其进行字段检查:

func printStructTags(f reflect.Value) { // f is of struct type `human`
    for i := 0; i < f.NumField(); i++ {
        fmt.Printf("Tags are %s\n", f.Type().Field(i).Tag) 
    }
}

但是,使用 f.type().field(i).tag.get("anonymize") 检查标签并获取其值会更容易。通过这种方式,您可以直接获取分配的值,例如,在您的情况下为 true ,如果标签不存在,则为空字符串。

好了,本文到此结束,带大家了解了《从Go结构中提取标签作为reflect.Value》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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