检查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())
}
输出:
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()
其标识为slice
?
慕运维8079593
相关分类