Consider a Config struct with multiple fields. You have two structs of this type, DefaultConfig with default values and FileConfig loaded from a file. The goal is to merge these structs, giving priority to values in FileConfig while preserving unset fields.
One approach involves using reflection to compare field values and selectively update those in DefaultConfig:
func merge(default *Config, file *Config) (*Config) { b := reflect.ValueOf(default).Elem() o := reflect.ValueOf(file).Elem() for i := 0; i < b.NumField(); i++ { defaultField := b.Field(i) fileField := o.Field(i) if defaultField.Interface() != reflect.Zero(fileField.Type()).Interface() { defaultField.Set(reflect.ValueOf(fileField.Interface())) } } return default }
However, this method requires careful handling of zero values, as it could lead to unintended overwrites.
A more elegant and zero-effort solution utilizes the encoding/json package:
import ( "encoding/json" "io/ioutil" ) var defConfig = &Config{ S1: "def1", S2: "def2", S3: "def3", } func main() { fileContent, err := ioutil.ReadFile("config.json") if err != nil { panic(err) } err = json.NewDecoder(bytes.NewReader(fileContent)).Decode(&defConfig) if err != nil { panic(err) } fmt.Printf("%+v", defConfig) }
With this approach:
The above is the detailed content of How to Efficiently Merge Go Structs While Prioritizing Specific Values?. For more information, please follow other related articles on the PHP Chinese website!