Created
August 16, 2018 01:48
-
-
Save dulao5/0329590405418ec2f3405ab367ddfdce to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"reflect" | |
) | |
func main() { | |
vars := []interface{}{"1", "2", "3", "4", "5"} | |
fmt.Println(vars) | |
targetType := reflect.TypeOf([]string{}) | |
rSlice := reflect.MakeSlice(targetType, len(vars), len(vars)) | |
for index, item := range vars { | |
targetItem := rSlice.Index(index) | |
fmt.Println(targetItem.Interface()) | |
srcItem := reflect.ValueOf(item) | |
targetItem.Set(srcItem) | |
} | |
fmt.Println("copy to:") | |
fmt.Println(rSlice) // [1 2 3 4 5] | |
} |
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
# from : https://stackoverflow.com/questions/7850140/how-do-you-create-a-new-instance-of-a-struct-from-its-type-at-run-time-in-go | |
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()) | |
} |
Author
dulao5
commented
Nov 24, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment