Last active
June 29, 2022 11:03
-
-
Save snail007/4e98c8de1d079a9eed54dc7c890aae02 to your computer and use it in GitHub Desktop.
动态创建任何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 "reflect" | |
import "fmt" | |
type User struct { | |
Name string | |
} | |
func main() { | |
users := con([]User{}) | |
for _, u := range users { | |
user := u.(User) | |
fmt.Println(user) | |
} | |
} | |
func con(data interface{}) (structs []interface{}) { | |
typ := reflect.TypeOf(data).Elem() | |
arr := reflect.New(reflect.TypeOf(data)).Elem() | |
for i := 0; i < 5; i++ { | |
v := reflect.New(typ).Elem() | |
f := v.Field(0) | |
f.SetString("test") | |
arr = reflect.Append(arr, v) | |
} | |
structs = []interface{}{} | |
for i := 0; i < arr.Len(); i++ { | |
structs = append(structs, arr.Index(i).Interface()) | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment