i0n
i0n

Reputation: 926

Create slice of pointers using reflection in Go

I've seen a few examples of reflection around this topic, but I can't find anything that solves this issue. It feels a little convoluted, but the alternative is a massive amount of repetition so I thought I'd give it a try.

I have a function that returns a function (handler). The wrapping function passes in an instance of a struct. I need the inner function to create a slice of pointers to that struct type:

func createCollectionHandler(app *appSession, record interface{}, name string) func(res http.ResponseWriter, req *http.Request) {
    return func(res http.ResponseWriter, req *http.Request) {
        res.Header().Set("Content-Type", "application/json")

        // This line needs to be dynamic:
        var result []*Person

        err := meddler.QueryAll(app.MysqlDB, &result, "select * from "+name)
        if err != nil {
            log.Fatal(err)
        }
        json, err := json.MarshalIndent(result, "", " ")
        if err != nil {
            log.Println(err)
        }
        res.Write([]byte(json))
        return
    }
}

Upvotes: 2

Views: 1815

Answers (1)

JimB
JimB

Reputation: 109330

You can create a slice using reflect and an example of the type like so:

var t *MyType

typeOfT := reflect.TypeOf(t)
sliceOfT := reflect.SliceOf(typeOfT)

s := reflect.MakeSlice(sliceOfT, 0, 0).Interface()

In order to pass a pointer to the slice without knowing the type, you can create the pointer first, then set the slice value:

ptr := reflect.New(sliceOfT)
ptr.Elem().Set(reflect.MakeSlice(sliceOfT, 0, 0))
s := ptr.Interface()

http://play.golang.org/p/zGSqe45E60

Upvotes: 5

Related Questions