vendredi 29 novembre 2019

go: Howto derive an array of struct from any struct type - getting from interface{} to []interface{}?

I try to implement a function taking (any) structure, returning an array of those structures. ReturnArrayOfStory show the idea with a fixed type struct type.

trying to do the same for any type with function ReturnArrayOfX and reflection fails at compile time.

package main

import (
    "fmt"
    "reflect"
)
type story_t struct {
    LANGUAGE string
    SPECIES  string
}

func ReturnArrayOfStory(x story_t) []story_t {
    x1 := x
    var a1 []story_t
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    return a1
}

func ReturnArrayOfX(x interface{}) []interface{} {
    x1 := x
    v1 := reflect.ValueOf(&x1).Elem()
    a1 := []reflect.TypeOf(&x1)
    //  var a1 []x
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    //return a1
    return a1
}

func main() {

    var as1 []story_t

    s1 := story_t{"EN", "Prince of Persia"}

    as1 = ReturnArrayOfStory(s1)
    //as1 := ReturnArrayOfX(s1)
    for i := 0; i < len(as1); i++ {
        fmt.Printf("%02d %+v\n", i, as1[i])
    }

    as2 := ReturnArrayOfX(s1)
    //as1 := ReturnArrayOfX(s1)
    for i := 0; i < len(as2); i++ {
        fmt.Printf("%02d %+v\n", i, as2[i])
    }

}

a1 := []reflect.TypeOf(&x1)
main.go:25:8: reflect.TypeOf is not a type

This is a simplified szenario. In real I like to read a multitude of struct types from an external datasource like a database.

  • How can I came to my goal with ReturnArrayOfX?
  • List item Is this possible? If not,strong text why?




Aucun commentaire:

Enregistrer un commentaire