-1

结构可能包含 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)
}
4

1 回答 1

0

你可以这样做:

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

于 2020-04-27T10:59:53.077 回答