How to cast reflect.Value to its type?

后端 未结 4 1518
离开以前
离开以前 2021-01-31 07:50

How to cast reflect.Value to its type?

type Cat struct { 
    Age int
}

cat := reflect.ValueOf(obj)
fmt.Println(cat.Type()) // Cat

fmt.Println(Cat(cat).Age) //         


        
4条回答
  •  青春惊慌失措
    2021-01-31 08:19

    concreteCat,_ := reflect.ValueOf(cat).Interface().(Cat)
    

    see http://golang.org/doc/articles/laws_of_reflection.html fox example

    type MyInt int
    var x MyInt = 7
    v := reflect.ValueOf(x)
    y := v.Interface().(float64) // y will have type float64.
    fmt.Println(y)
    

提交回复
热议问题