如何将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
Run Code Online (Sandbox Code Playgroud)
谢谢!
sha*_*ind 45
concreteCat,_ := reflect.ValueOf(cat).Interface().(Cat)
Run Code Online (Sandbox Code Playgroud)
请参阅http://golang.org/doc/articles/laws_of_reflection.html fox示例
type MyInt int
var x MyInt = 7
v := reflect.ValueOf(x)
y := v.Interface().(float64) // y will have type float64.
fmt.Println(y)
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 26
好的,我找到了
reflect.Value有一个Interface()将其转换为的函数interface{}
此 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())
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34045 次 |
| 最近记录: |