Skip to content

Instantly share code, notes, and snippets.

@theophoric
Created March 11, 2014 00:13
Show Gist options
  • Save theophoric/9477116 to your computer and use it in GitHub Desktop.
Save theophoric/9477116 to your computer and use it in GitHub Desktop.
setting dynamic content into struct
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