Created
January 7, 2022 18:43
-
-
Save Plankiton/aaa5544237d57281cbd36e240d31b815 to your computer and use it in GitHub Desktop.
Setting Struct Field Dinamicaly Using Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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