![](/img/trans.png)
[英]How to create an object of interface value type in go using reflection
[英]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()) // 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
}
因此,有没有办法识别arrValue是切片值而不是interface {}值? https://play.golang.org/p/R_sPR2JbQx
如您所见,您不能直接附加到接口。 因此,您想要获取与接口关联的值,然后将其与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.