lundi 12 août 2019

Using Go lang reflection to populate a pointer to a struct

I'd like to iterate over the fields in a struct and prompt for string values to string fields, doing this recursively for fields that are pointers to structs.

Currently this is what I've tried, but I get an error when trying to set this value in the pointer's string field.

package main

import (
    "fmt"
    "reflect"
)

type Table struct {
    PK *Field
}

type Field struct {
    Name string
}


func main() {
    PopulateStruct(&Table{})
}

func PopulateStruct(a interface{}) interface {} {
    typeOf := reflect.TypeOf(a)
    valueOf := reflect.ValueOf(a)
    for i := 0; i < typeOf.Elem().NumField(); i++ {
        switch typeOf.Elem().Field(i).Type.Kind() {
        case reflect.String:
            fmt.Print(typeOf.Elem().Field(i).Name)
            var s string
            fmt.Scanf("%s", &s)
            valueOf.Elem().Field(i).SetString(s)
        case reflect.Ptr:
            ptr := reflect.New(valueOf.Elem().Field(i).Type())
            PopulateStruct(ptr.Elem().Interface())
            valueOf.Elem().Field(i).Set(ptr)
        }
    }
}

Expecting the return value to include an initialised struct with the pointers string field set.

Getting an error when setting the pointer's string field.

panic: reflect: call of reflect.Value.Field on zero Value





Aucun commentaire:

Enregistrer un commentaire