Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement