[英]`reflect.Kind()` of Slice Becomes `Struct` When Stored Inside Pointer
When checking the reflect.Kind()
of a slice, reflect
correctly identifies it as a slice
when not stored inside a pointer:当检查一个切片的reflect.Kind()
时,如果没有存储在一个指针中, reflect
正确地将它识别为一个slice
:
package main
import (
"fmt"
"reflect"
)
type Dog struct {
Name string
Age int
}
func main() {
var dogs []Dog
rDogs := reflect.ValueOf(dogs)
fmt.Println(rDogs.Kind())
}
Output:输出:
slice
However, when a slice is stored inside a pointer, reflect.Kind()
identifies it as a struct
:但是,当切片存储在指针中时, reflect.Kind()
将其标识为struct
:
package main
import (
"fmt"
"reflect"
)
type Dog struct {
Name string
Age int
}
func main() {
dogs1 := make([]Dog, 0)
pointer := &dogs1
printPointerValueKind(pointer)
var dogs2 []Dog
pointer = &dogs2
printPointerValueKind(pointer)
}
func printPointerValueKind(pointer interface{}) {
if pointer != nil {
rPointer := reflect.ValueOf(pointer)
if rPointer.Kind() == reflect.Ptr {
value := rPointer.Elem()
rValue := reflect.ValueOf(value)
fmt.Println(rValue.Kind())
}
}
}
Output:输出:
struct
struct
My questions are:我的问题是:
Why does this happen?为什么会发生这种情况?
Is there a way to store a slice inside a pointer and still have reflect.Kind()
identify it as a slice
?有没有办法将一个切片存储在一个指针中,并且仍然有reflect.Kind()
将它标识为一个slice
?
1 . 1 . (reflect.Value).Elem()
returns a reflect.Value
, which is a struct, and which does not need to be passed to reflect.ValueOf
again if you're looking for the kind of the type that the value holds. (reflect.Value).Elem()
返回一个reflect.Value
,这是一个结构,而这并不需要传递给reflect.ValueOf
,如果你正在寻找的那种值保持类型的一次。
2 . 2 . rPointer.Elem().Kind()
should be enough for what you need. rPointer.Elem().Kind()
应该足以满足您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.