Skip to content

Instantly share code, notes, and snippets.

@mopemope
Created July 26, 2013 02:13
Show Gist options
  • Select an option

  • Save mopemope/6085524 to your computer and use it in GitHub Desktop.

Select an option

Save mopemope/6085524 to your computer and use it in GitHub Desktop.
reflect example
package main
import (
"log"
"reflect"
"strings"
)
type Person struct {
Name string
Age uint
}
func SetValue(typ reflect.Value, data string) {
kv := strings.Split(data, ":")
if len(kv) != 2 {
return
}
key := strings.TrimSpace(kv[0])
field := typ.FieldByName(key)
if !field.CanSet() {
return
}
field.SetString(strings.TrimSpace(kv[1]))
}
func main() {
p := &Person{
Name: "aa",
Age: 3,
}
s := reflect.ValueOf(p).Elem()
log.Println(p)
SetValue(s, "Name: AAA ")
SetValue(s, "Foo: AAA")
log.Println(p.Name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment