agnor
agnor

Reputation: 369

Go lang reflection how to recognize interface underlying type

For instance :

package main

import (
    "fmt"
    "reflect"
)

func main() {

    arr := []int{}

    var arrI interface{} = arr

    arrValuePtr := reflect.ValueOf(&arrI)
    arrValue := arrValuePtr.Elem()

    fmt.Println("Type: ", arrValue.Type()) // prints: "Type: interface{}
    fmt.Println("Interface value: ", arrValue.Interface()) // prints: "Interface value: []"


    arrValue.Set(reflect.Append(arrValue, reflect.ValueOf(55))) 
    // error: panic: reflect: call of reflect.Append on interface Value
}

So is there a way to recognize that arrValue is a slice value rather than interface{} value? https://play.golang.org/p/R_sPR2JbQx

Upvotes: 1

Views: 859

Answers (1)

Fabien
Fabien

Reputation: 13406

As you have seen, you cannot directly append to the interface. So, you want to get the value associated with the interface and then use it with Value.Append.

arr := []int{}

var arrI interface{} = arr

arrValuePtr := reflect.ValueOf(&arrI)
arrValue := arrValuePtr.Elem()

fmt.Println("Type: ", arrValue.Type()) // prints: "Type: interface{}
fmt.Println("Interface value: ", arrValue.Interface()) // prints: "Interface value: []"
fmt.Println(reflect.ValueOf(arrValue.Interface()))
arr2 := reflect.ValueOf(arrValue.Interface())
arr2 = reflect.Append(arr2, reflect.ValueOf(55))
fmt.Println(arr2) // [55]

Upvotes: 2

Related Questions