doushen2154
2013-06-23 15:23
浏览 2.1k
已采纳

如何将reflect.Value转换为其类型?

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) // doesn't compile
fmt.Println((cat.(Cat)).Age) // same

Thanks!

图片转代码服务由CSDN问答提供 功能建议

如何将reflect.Value强制转换为其类型?

  类型Cat struct {
 Age int 
} 
 
cat:= reflect.ValueOf(obj)
fmt.Println(cat.Type())// Cat 
 
fmt.Println(Cat(cat).Age  )//不编译
fmt.Println((cat。(Cat))。Age)//相同
   
 
 

谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongsi2317 2013-06-23 15:32
    已采纳

    Ok, I found it

    reflect.Value has a function Interface() that converts it to interface{}

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dpzlz08480 2013-12-19 08:05
    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)
    
    评论
    解决 无用
    打赏 举报
  • doujupa7567 2018-08-23 02:05

    Seems the only way would be to do a switch statement similar to (code below) (also, something like the commented line would've-been nice though doesn't work (:()):

    func valuesFromStruct (rawV interface{}) []interface{} {
        v := reflect.ValueOf(rawV)
        out := make([]interface{}, 0)
        for i := 0; i < v.NumField(); i += 1 {
            field := v.Field(i)
            fieldType := field.Type()
            // out = append(out, field.Interface().(reflect.PtrTo(fieldType)))
            switch (fieldType.Name()) {
            case "int64":
                out = append(out, field.Interface().(int64))
                break`enter code here`
            case "float64":
                out = append(out, field.Interface().(float64))
                break
            case "string":
                out = append(out, field.Interface().(string))
                break
            // And all your other types (here) ...
            default:
                out = append(out, field.Interface())
                break
            }
        }
        return out
    }
    

    Cheers!

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题