例如:
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是一个切片值,而不是接口{}值?https://play.golang.org/p/R_sPR2JbQx
发布于 2017-03-05 19:43:10
正如您所看到的,您不能直接附加到接口。因此,您希望获取与接口关联的值,然后将其与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]https://stackoverflow.com/questions/42607069
复制相似问题