-
-
Save sdhjl2000/fb23c13ef76effbbb4ae to your computer and use it in GitHub Desktop.
golang new obj
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 Config struct { | |
Name string | |
Meta struct { | |
Desc string | |
Properties map[string]string | |
Users []string | |
} | |
} | |
func initializeStruct(t reflect.Type, v reflect.Value) { | |
for i := 0; i < v.NumField(); i++ { | |
f := v.Field(i) | |
ft := t.Field(i) | |
switch ft.Type.Kind() { | |
case reflect.Map: | |
f.Set(reflect.MakeMap(ft.Type)) | |
case reflect.Slice: | |
f.Set(reflect.MakeSlice(ft.Type, 0, 0)) | |
case reflect.Chan: | |
f.Set(reflect.MakeChan(ft.Type, 0)) | |
case reflect.Struct: | |
initializeStruct(ft.Type, f) | |
case reflect.Ptr: | |
fv := reflect.New(ft.Type.Elem()) | |
initializeStruct(ft.Type.Elem(), fv.Elem()) | |
f.Set(fv) | |
default: | |
} | |
} | |
} | |
func main() { | |
t := reflect.TypeOf(Config{}) | |
v := reflect.New(t) | |
initializeStruct(t, v.Elem()) | |
c := v.Interface().(*Config) | |
c.Meta.Properties["color"] = "red" // map was already made! | |
c.Meta.Users = append(c.Meta.Users, "srid") // so was the slice. | |
fmt.Println(v.Interface()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment