Golang反射:从结构字段获取标签

编程入门 行业动态 更新时间:2024-10-22 04:24:36
本文介绍了Golang反射:从结构字段获取标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在结构的某个字段上进行反思,并获得对其标记值的引用?

Is it possible to reflect on a field of a struct, and get a reference to its tag values?

例如:

type User struct { name string `json:name-field` age int } ... user := &User{"John Doe The Fourth", 20} getStructTag(user.name) ... func getStructTag(i interface{}) string{ //get tag from field }

从我所看到的,执行此操作的通常方法是在typ.NumField()范围内,然后调用field.Tag.Get("tagname").但是,在我的用例中,最好不必传递整个结构.有什么想法吗?

From what I can see, the usual way to do this is to range over typ.NumField(), and then call field.Tag.Get("tagname"). However, in my use-case, it would be much better to not have to pass the whole struct in. Any ideas?

推荐答案

您不需要传入整个结构,但是传入其中一个字段的值是不够的.

You don't need to pass in the whole struct, but passing in the value of one of the fields is not sufficient.

在您的示例中, user.name 字段只是一个 string -反射包将无法将其与原始结构相关联.

In your example user.name field is just a string - the reflect package will have no way of correlating that back to the original struct.

相反,您需要传递给定字段的 reflect.StructField :

Instead, you need to pass around the reflect.StructField for the given field:

field, ok := reflect.TypeOf(user).Elem().FieldByName("name") … tag = string(field.Tag)

注意:我们使用上面的 Elem ,因为 user 是指向结构的指针.

Note: we use Elem above because user is a pointer to a struct.

您可以在此处查看示例.

更多推荐

Golang反射:从结构字段获取标签

本文发布于:2023-07-30 00:34:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射   结构   标签   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!