2 回答
TA贡献1773条经验 获得超3个赞
要获取结构值,您需要获取接口值的元素:
fmt.Println("Indirect type is:", reflect.Indirect(reflect.ValueOf(v)).Elem().Type()) // prints main.CustomStruct
fmt.Println("Indirect value type is:", reflect.Indirect(reflect.ValueOf(v)).Elem().Kind()) // prints struct
此代码有助于理解示例中的类型:
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
fmt.Println(rv.Kind(), rv.Type(), rv)
rv = rv.Elem()
}
if rv.IsValid() {
fmt.Println(rv.Kind(), rv.Type(), rv)
}
输出为&s:
ptr *interface {} 0xc000010200
interface interface {} {}
struct main.CustomStruct {}
TA贡献1878条经验 获得超4个赞
使用reflect.Indirect
package main
import (
"fmt"
"reflect"
)
func testFunc(value interface{}) {
fmt.Println("---------------------")
fmt.Println("type = " + reflect.ValueOf(value).Type().String())
fmt.Println("kind = " + reflect.ValueOf(value).Kind().String())
if reflect.ValueOf(value).Kind() == reflect.Ptr {
fmt.Println("--> pointer ")
pointsToValue := reflect.Indirect(reflect.ValueOf(value))
fmt.Println("-->", pointsToValue.Kind(), " - ", pointsToValue.Type(), " - ", pointsToValue)
if pointsToValue.Kind() == reflect.Slice {
fmt.Println("--> slice !! ")
}
}
}
func main() {
var testVar1 string
var testVar2 []string
var testVar3 []*string
testVar2 = append(testVar2, "A")
testVar2 = append(testVar2, "B")
testFunc(testVar1)
testFunc(testVar2)
testFunc(testVar3)
testFunc(testVar2)
testFunc(&testVar2)
}
/*
---------------------
type = string
kind = string
---------------------
type = []string
kind = slice
---------------------
type = []*string
kind = slice
---------------------
type = []string
kind = slice
---------------------
type = *[]string
kind = ptr
--> pointer
--> slice - []string - [A B]
--> slice !!
*/
https://play.golang.org/p/ysqIWQYyzn3
- 2 回答
- 0 关注
- 194 浏览
添加回答
举报