go 通过 structtag 反射查找

type A struct {

    Name *NameS `json:"name"`

}

对于结构 A,是否有一种方法可以通过 structtag 找到字段,例如


reflect.ValueOf(&ns)

// struct

s := ps.Elem()

s.FieldByTag("name")


宝慕林4294392
浏览 73回答 1
1回答

月关宝盒

没有内置方法/函数可以执行此操作。中的现有FieldBy*方法reflect是作为循环实现的(参见`src/reflect/type.go)。您还可以编写一个循环来实现此处所需的功能。一种方法可能是这样的:func fieldByTag(s interface{}, tagKey, tagValue string) (reflect.StructField, bool) {&nbsp; &nbsp; rt := reflect.TypeOf(s)&nbsp; &nbsp; for i := 0; i < rt.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; field := rt.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; if field.Tag.Get(tagKey) == tagValue {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return field, true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return reflect.StructField{}, false}请注意,tagKey和tagValue是单独传递的,因为这就是reflect.StructField工作原理。所以在你的情况下你会这样称呼它:field, ok := fieldByTag(&ns, "json", "name")
打开App,查看更多内容
随时随地看视频慕课网APP