gpt4 book ai didi

go - 如何使用反射将值分配给未知结构

转载 作者:行者123 更新时间:2023-12-01 22:36:35 24 4
gpt4 key购买 nike

结构可以包含float32,int32,字符串或指向结构的指针。
这是我的代码。但是我不知道如何给里面的结构赋值。


type T struct {
A int
B string
C *P
}

type P struct {
A string
B int
}

func main() {
t := T{}
decode(&t, []string{"99", "abc", "abc", "99"})
fmt.Println(t)
}

最佳答案

您可以执行以下操作:

func decode(a interface{}, val []string) {
rdecode(reflect.ValueOf(a).Elem(), val)
}

func rdecode(rv reflect.Value, val []string) int {
var index int
for i := 0; i < rv.NumField(); i++ {
f := rv.Field(i)

if f.Kind() == reflect.Ptr {
if f.IsNil() {
f.Set(reflect.New(f.Type().Elem()))
}
f = f.Elem()
}

switch f.Kind() {
case reflect.Int:
tmp, _ := strconv.Atoi(val[index])
f.Set(reflect.ValueOf(tmp))
index++
case reflect.String:
f.SetString(val[index])
index++
case reflect.Struct:
index += rdecode(f, val[index:])
default:
break
}
}
return index
}

https://play.golang.com/p/Jyj0flzDBhu

关于go - 如何使用反射将值分配给未知结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com