vendredi 24 mars 2023

Universal solution for changing structures using reflection

Suppose I have a structure with several nested structures:

type SomeInt int
type AnotherConfig struct {
    Value1 string
    Value2 int
    Value3 SomeInt
}
type SubConf struct {
    Value1 string
    Value2 int
    Conf   AnotherConfig
}
type Config struct {
    Value1 string
    Value2 int
    Conf   SubConf
}

I need an implementation of a function that will take as input a path from some final scalar field, and set there a value that will automatically be converted to the appropriate type:

func (conf *Config) ChangeValue(path string, value string) {
    //Need implementation
}

func main() {
    conf := Config{}
    // Usage example:
    conf.ChangeValue("Conf.Conf.Value3", "123")
}

Nested structures can constantly change during development, so a more or less universal solution is needed. Perhaps with support for a limited set of type conversions, such as support for only strings and ints, but they can be typed (as in the example).





Aucun commentaire:

Enregistrer un commentaire