Skip to content

Instantly share code, notes, and snippets.

@mmcloughlin
Created October 28, 2016 02:43
Show Gist options
  • Select an option

  • Save mmcloughlin/5cbff0d97332d122603b17e7a45c39d5 to your computer and use it in GitHub Desktop.

Select an option

Save mmcloughlin/5cbff0d97332d122603b17e7a45c39d5 to your computer and use it in GitHub Desktop.
Golang Struct Tags
package main
import (
"fmt"
"reflect"
)
// PrintTags prints all tag values for the given struct.
func PrintTags(s interface{}, tag string) {
st := reflect.TypeOf(s)
for i := 0; i < st.NumField(); i++ {
f := st.Field(i)
fmt.Printf("field=%s\t%s=%s\n", f.Name, tag, f.Tag.Get(tag))
}
}
// Populate sets values of the input struct by using a struct tag as a key
// into a values map.
func Populate(s interface{}, tag string, values map[string]string) {
st := reflect.TypeOf(s).Elem()
v := reflect.ValueOf(s).Elem()
for i := 0; i < st.NumField(); i++ {
f := st.Field(i)
key := f.Tag.Get(tag)
value := values[key]
v.Field(i).SetString(value)
}
}
type Example struct {
A string `namespace:"hello"`
B string `namespace:"world"`
}
func main() {
e := Example{}
PrintTags(e, "namespace")
values := map[string]string{
"hello": "a",
"world": "b",
}
fmt.Println(e)
Populate(&e, "namespace", values)
fmt.Println(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment