简体   繁体   English

去lang反射如何识别接口基础类型

[英]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? 因此,有没有办法识别arrValue是切片值而不是interface {}值? https://play.golang.org/p/R_sPR2JbQx https://play.golang.org/p/R_sPR2JbQx

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 . 因此,您想要获取与接口关联的值,然后将其与Value.Append一起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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM