Search code examples
gointerfaceslicereflect

Generic function which appends two arrays


Not able to figure out how to convert interface{} returned from function into an array of structs

As part of some practise i was trying to create a function which can take 2 slices of some type and concatenates both and returns the slice.

The code can be found here - https://play.golang.org/p/P9pfrf_qTS1

type mystruct struct {
    name  string
    value string
}

func appendarr(array1 interface{}, array2 interface{}) interface{} {
    p := reflect.ValueOf(array1)
    q := reflect.ValueOf(array2)
    r := reflect.AppendSlice(p, q)
    return reflect.ValueOf(r).Interface()
}

func main() {
    fmt.Println("=======")
    array1 := []mystruct{
        mystruct{"a1n1", "a1v1"},
        mystruct{"a1n2", "a1v2"},
    }
    array2 := []mystruct{
        mystruct{"a2n1", "a2v1"},
        mystruct{"a2n2", "a2v2"},
    }
    arrayOp := appendarr(array1, array2)
    fmt.Printf("arr: %#v\n", arrayOp) // this shows all the elements from array1 and 2
    val := reflect.ValueOf(arrayOp)
    fmt.Println(val)                          // output is <[]main.mystruct Value>
    fmt.Println(val.Interface().([]mystruct)) // exception - interface {} is reflect.Value, not []main.mystruct
}

I may have slices of different types of structs. I want to concatenate them and access the elements individually. If there is any other way of achieving the same, please do let me know.


Solution

  • reflect.Append() returns a value of type reflect.Value, so you don't have to (you shouldn't) pass that to reflect.ValueOf().

    So simply change the return statement to:

    return r.Interface()
    

    With this it works and outputs (try it on the Go Playground):

    =======
    arr: []main.mystruct{main.mystruct{name:"a1n1", value:"a1v1"}, main.mystruct{name:"a1n2", value:"a1v2"}, main.mystruct{name:"a2n1", value:"a2v1"}, main.mystruct{name:"a2n2", value:"a2v2"}}
    [{a1n1 a1v1} {a1n2 a1v2} {a2n1 a2v1} {a2n2 a2v2}]
    [{a1n1 a1v1} {a1n2 a1v2} {a2n1 a2v1} {a2n2 a2v2}]
    

    You also don't need to do any reflection-kungfu on the result: it's your slice wrapped in interface{}. Wrapping it in reflect.Value and calling Value.Interface() on it is just a redundant cycle. You may simply do:

    arrayOp.([]mystruct)
    

    On a side note: you shouldn't create a "generic" append() function that uses reflection under the hood, as this functionality is available as a built-in function append(). The builtin function is generic, it gets help from the compiler so it provides the generic nature at compile-time. Whatever you come up with using reflection will be slower.