Skip to content

Instantly share code, notes, and snippets.

@Plankiton
Created January 7, 2022 18:43
Show Gist options
  • Select an option

  • Save Plankiton/aaa5544237d57281cbd36e240d31b815 to your computer and use it in GitHub Desktop.

Select an option

Save Plankiton/aaa5544237d57281cbd36e240d31b815 to your computer and use it in GitHub Desktop.
Setting Struct Field Dinamicaly Using Go
package main
import (
"fmt"
"reflect"
)
type Config struct {
A string `default:"joao"`
B string `default:"maria"`
}
func NewConfig() Config {
config := Config{"JDSLKJFLKSJDKLFKLDS;lfj;als", ""}
configT := reflect.TypeOf(config)
configV := reflect.ValueOf(&config)
for f := 0; f < configT.NumField(); f++ {
fieldInfo := configT.Field(f)
field := configV.Elem().Field(f)
if field.Interface().(string) == "" {
defaultValue := fieldInfo.Tag.Get("default")
field.SetString(defaultValue)
}
}
return config
}
func main() {
j := NewConfig()
fmt.Printf("%+v", j)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment