Go语言反射如何识别接口的底层类型

huangapple go评论76阅读模式
英文:

Go lang reflection how to recognize interface underlying type

问题

例如:

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()) // 输出: "Type: interface{}"
    fmt.Println("Interface value: ", arrValue.Interface()) // 输出: "Interface value: []"


    arrValue.Set(reflect.Append(arrValue, reflect.ValueOf(55))) 
    // 错误: panic: reflect: 在接口值上调用 reflect.Append
}

那么有没有办法识别 arrValue 是切片值而不是 interface{} 值呢?
https://play.golang.org/p/R_sPR2JbQx

英文:

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

答案1

得分: 2

如您所见,您无法直接向接口追加内容。因此,您想要获取与接口关联的值,然后使用Value.Append进行操作。

arr := []int{}

var arrI interface{} = arr

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

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

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]

huangapple
  • 本文由 发表于 2017年3月5日 18:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42607069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定