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

时间:2013-06-23 15:23:45

标签: reflection go

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

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

谢谢!

4 个答案:

答案 0 :(得分:41)

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

http://golang.org/doc/articles/laws_of_reflection.html 狐狸的例子

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

答案 1 :(得分:18)

好的,我找到了

reflect.Value有一个函数Interface(),可将其转换为interface{}

答案 2 :(得分:1)

此功能可以根据需要自动转换类型。它将根据结构名称和字段将配置文件值加载到一个简单的结构中:

import (
    "fmt"
    toml "github.com/pelletier/go-toml"
    "log"
    "os"
    "reflect"
)
func LoadConfig(configFileName string, configStruct interface{}) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("LoadConfig.Recovered: ", r)
        }
    }()
    conf, err := toml.LoadFile(configFileName)
    if err == nil {
        v := reflect.ValueOf(configStruct)
        typeOfS := v.Elem().Type()
        sectionName := getTypeName(configStruct)
        for i := 0; i < v.Elem().NumField(); i++ {
            if v.Elem().Field(i).CanInterface() {
                kName := conf.Get(sectionName + "." + typeOfS.Field(i).Name)
                kValue := reflect.ValueOf(kName)
                if (kValue.IsValid()) {
                    v.Elem().Field(i).Set(kValue.Convert(typeOfS.Field(i).Type))
                }
            }
        }
    } else {
        fmt.Println("LoadConfig.Error: " + err.Error())
    }
}

答案 3 :(得分:-1)

似乎唯一的方法是执行类似于{下面的代码)的switch语句(此外,诸如注释行之类的东西虽然不起作用(:())还是不错的: / p>

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
}

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 }

干杯!