[英]`reflect.Kind()` of Slice Becomes `Struct` When Stored Inside 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())
}
輸出:
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
?
1 . (reflect.Value).Elem()
返回一個reflect.Value
,這是一個結構,而這並不需要傳遞給reflect.ValueOf
,如果你正在尋找的那種值保持類型的一次。
2 . rPointer.Elem().Kind()
應該足以滿足您的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.