How to cast reflect.Value to its type?

后端 未结 4 1446
离开以前
离开以前 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:20

    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!

提交回复
热议问题