How to cast reflect.Value to its type?

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

    This func auto-converts types as needed. It loads a config file values into a simple struct based on struct name and fields:

    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())
        }
    }
    

提交回复
热议问题