Home >Backend Development >Golang >How Can I Efficiently Merge Two Identical Go Structs, Prioritizing Non-Zero Values from the Second Struct?
The task is to merge two structs of the same type such that fields in the second struct override those in the first, but only if they are set. The solution should take into account the possibility of zero values.
An initial approach considers using reflection:
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 approach faces concerns regarding the use of reflection and the difficulty in checking for zero values in all cases.
An alternative solution leverages the encoding/json package:
conf := new(Config) // New config *conf = *defConfig // Initialize with defaults err := json.NewDecoder(strings.NewReader(fileContent)).Decode(&conf) if err != nil { panic(err) }
This approach offers several advantages:
Using this approach with the given default configuration and file content produces the following output:
&{S1: S2:file-s2 S3: S4:def S5:file-s5}
This demonstrates that:
The above is the detailed content of How Can I Efficiently Merge Two Identical Go Structs, Prioritizing Non-Zero Values from the Second Struct?. For more information, please follow other related articles on the PHP Chinese website!