mardi 20 juillet 2021

Unmarshal list of arbitrary struct and append it to slice with reflection

I would like to unmarshal a JSON string which will be a list of an arbitrary struct (determined at runtime), and append the unmarshalled list of structs to a slice supplied to the function (the type is unknown before runtime, but is a slice of the same time of the list being unmarshalled).

Here is a minimal example of what I'm trying to achieve (playground link here):

type Foo struct {
    Name string
}

func get(results interface{}) (interface{}, error) {
    resVal := reflect.ValueOf(results)
    data := reflect.New(resVal.Type())

    err := json.Unmarshal([]byte(`[{"name":"data"},{"name":"test"}]`), data.Interface())
    if err != nil {
        return nil, err
    }

    return reflect.Append(resVal, data).Interface(), nil
}

func main() {
    results := []Foo{}
    newResults, err := get(results)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%#v\n", newResults)
}

I believe the above should work, but I'm getting:

panic: reflect.Set: value of type *[]main.Foo is not assignable to type main.Foo




Aucun commentaire:

Enregistrer un commentaire