dimanche 10 mai 2020

Golang reflection slice shows up as struct

package main

import (
    "fmt"
    "encoding/json"
    "reflect"
)

func someFunc( data interface{}, out interface{} ) {
    v := reflect.ValueOf(out).Elem();
    fmt.Printf("Incoming type: %s\n",reflect.ValueOf(v).Kind())
    v.SetCap(reflect.ValueOf(data).Len())
}

func main() {
    expected := []int{1,2,3}

    jsonRaw, _ := json.Marshal(expected)
    var tmpData interface{}

    json.Unmarshal(jsonRaw, &tmpData)
    fmt.Printf("%s\n",string(jsonRaw))
    fmt.Printf("%#v\n",tmpData)

    result := []int{}
    var tmp interface{}
    tmp = result
    fmt.Printf("Outcoming type: %s\n",reflect.TypeOf(&tmp))
    someFunc(tmpData,&tmp)
}

I would like to operate on v parameter inside someFunc as if it were a slice, i.e. "Incoming type"-debug message should output slice. However, it outputs struct, as is shown here. The ultimate goal is that I use reflection to analyze the data-parameter's contents and recover everything into out, but for now I would like to know how to make sure the correct type of v is detected, so that I can use it as a slice.





Aucun commentaire:

Enregistrer un commentaire