英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论