如何在Golang中访问变量标签?

huangapple go评论110阅读模式
英文:

How to access variable tags in golang?

问题

我很好奇如何在Golang中访问变量标签。我知道JSON使用它们的方式如下:

  1. type Foo struct {
  2. Bar string `json:"-"`
  3. }

但是我似乎找不到一种方法来在代码中访问这些标签以供我自己使用。我该如何获取这些值,以便在代码中使用它们?

英文:

I'm curious on how to access variable tags in golang. I know JSON uses them like this:

  1. type Foo struct {
  2. Bar string `json:"-"`
  3. }

But I can't seem to find a way to access those tags in code for my own use. How can I get those values so I can use them in code?

答案1

得分: 11

你可以使用反射(reflection)来实现。可以参考Go文档中的这个例子

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. type S struct {
  8. F string `species:"gopher" color:"blue"`
  9. }
  10. s := S{}
  11. st := reflect.TypeOf(s)
  12. field := st.Field(0)
  13. fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
  14. }
英文:

You would use reflection. See this example from the go docs:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. type S struct {
  8. F string `species:"gopher" color:"blue"`
  9. }
  10. s := S{}
  11. st := reflect.TypeOf(s)
  12. field := st.Field(0)
  13. fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
  14. }

huangapple
  • 本文由 发表于 2015年10月30日 08:49:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/33427201.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定