Created
March 11, 2014 00:13
-
-
Save theophoric/9477116 to your computer and use it in GitHub Desktop.
setting dynamic content into struct
This file contains 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 ( | |
"fmt" | |
"reflect" | |
) | |
type Node struct { | |
Name string | |
Code int | |
} | |
func main() { | |
n := &Node{ | |
Name: "Foo", | |
Code: 1234, | |
} | |
vn := reflect.ValueOf(n) | |
params := map[string]interface{}{ | |
"Name": "Bar", | |
} | |
for fieldName, newVal := range params { | |
fmt.Print(fieldName, " :: ") | |
field := vn.Elem().FieldByName(fieldName) | |
if field.IsValid() { | |
fmt.Println("KIND -> ", field.Kind()) | |
fmt.Println("VALID") | |
if field.CanSet() { | |
fmt.Println("CAN SET") | |
vnewVal := reflect.ValueOf(newVal) | |
if field.Kind() == vnewVal.Kind() { | |
fmt.Println("KINDS MATCH") | |
field.Set(vnewVal) | |
} else { | |
fmt.Println("KINDS DO NOT MATCH") | |
} | |
} else { | |
fmt.Println("CAN NOT SET") | |
} | |
} else { | |
fmt.Println("NOT VALID") | |
} | |
} | |
fmt.Println("POST -->", n.Name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment