Created
July 26, 2013 02:13
-
-
Save mopemope/6085524 to your computer and use it in GitHub Desktop.
reflect example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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