检查reflect.Kind()切片的 时,如果未存储在指针内,reflect则正确将其识别为 a :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())
}
输出:
slice
但是,当切片存储在指针内时,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())
}
}
}
输出:
struct
struct
我的问题是:
为什么会出现这种情况?
有没有一种方法可以将切片存储在指针内,并且仍然将reflect.Kind()
其标识为 a slice
?
慕标5832272
相关分类