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

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

How to access variable tags in golang?

问题

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

type Foo struct {
    Bar string `json:"-"`
}

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

英文:

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

type Foo struct {
    Bar string `json:"-"`
}

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文档中的这个例子

package main

import (
	"fmt"
	"reflect"
)

func main() {
	type S struct {
		F string `species:"gopher" color:"blue"`
	}

	s := S{}
	st := reflect.TypeOf(s)
	field := st.Field(0)
	fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}
英文:

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

package main

import (
	"fmt"
	"reflect"
)

func main() {
	type S struct {
		F string `species:"gopher" color:"blue"`
	}

	s := S{}
	st := reflect.TypeOf(s)
	field := st.Field(0)
	fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))

}

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:

确定