56

如何将 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

4 回答 4

70
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)
于 2013-12-19T08:05:35.720 回答
37

好的,我找到了

reflect.Value具有Interface()将其转换为的功能interface{}

于 2013-06-23T15:32:37.933 回答
4

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

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())
    }
}
于 2020-01-02T18:13:34.197 回答
2

似乎唯一的方法是做一个switch类似于(下面的代码)的语句(另外,像注释行这样的东西虽然不起作用(:()),但会很好:

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
}

干杯!

于 2018-08-23T02:05:26.617 回答