mercredi 1 août 2018

Golang - Concatenate slices from pointer passed as interface

I'm working on a client for a specific API, and I built several structures (one for each route).
The API works with pages so I have getters returning slices of a struct. This is done passing through a common function that takes an interface supposed to be a pointer to a slice of the wanted structure so I can use Unmarshal from the json package.

The problem I'm facing is that I would like to get all the pages in a single request, but in order to do that I would need to concatenate several slices.

I tried to do this using reflect but I can only manage to create a new slice without actually altering the value that my interface is pointing to.

Here's a part of my code:

func concatenateSlice(dst, src interface{})(){
    dstValue := reflect.ValueOf(dst)
    srcValue := reflect.ValueOf(src)
    if srcValue.Type() != dstValue.Type(){
        return
    }
    switch srcValue.Kind(){
    case reflect.Ptr, reflect.Slice:
        dstValuePoint := reflect.Indirect(dstValue)
        srcValuePoint := reflect.Indirect(srcValue)
        reflect.Copy(dstValuePoint, reflect.AppendSlice(dstValuePoint, srcValuePoint))
    }
}

I'm sorry for the sloppy post, this is my first time on stackoverflow.





Aucun commentaire:

Enregistrer un commentaire