Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created September 28, 2014 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisguitarguy/c7a5240dde2923515243 to your computer and use it in GitHub Desktop.
Save chrisguitarguy/c7a5240dde2923515243 to your computer and use it in GitHub Desktop.
How to read struct tags in Go.
package main
import (
"errors"
"fmt"
"reflect"
)
var NotAStruct = errors.New("Object is Not a Struct")
type Example struct {
One string `test:"Yep"`
Two string `test:"Nope"`
Three string
}
func toReflection(obj interface{}) (reflect.Type, error) {
typ := reflect.TypeOf(obj)
if typ.Kind() != reflect.Struct {
return nil, NotAStruct
}
return typ, nil;
}
func main() {
e := Example{}
a := 1
if _, err := toReflection(a); err != nil {
fmt.Println(err)
}
typ, _ := toReflection(e)
for i := 0; i < typ.NumField(); i++ {
tag := typ.Field(i).Tag
fmt.Println(tag.Get("test"))
fmt.Println(tag.Get("doesnotexist"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment