Home >Backend Development >Golang >How Can I Efficiently Merge Two Identical Go Structs, Prioritizing Non-Zero Values from the Second Struct?

How Can I Efficiently Merge Two Identical Go Structs, Prioritizing Non-Zero Values from the Second Struct?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 16:04:15515browse

How Can I Efficiently Merge Two Identical Go Structs, Prioritizing Non-Zero Values from the Second Struct?

Merging Fields of Two Identical Structs

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.

Reflection-Based Approach

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.

JSON Unmarshaling Approach

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(&amp;conf)
if err != nil {
    panic(err)
}

This approach offers several advantages:

  • It automatically handles missing and zero values in the config file.
  • It preserves explicit overrides to zero values.

Analysis of Results

Using this approach with the given default configuration and file content produces the following output:

&amp;{S1: S2:file-s2 S3: S4:def S5:file-s5}

This demonstrates that:

  • S1, missing from the file, remains a zero value.
  • S2, specified in the file, overrides the default zero value.
  • S3, explicitly set to zero in the file, overrides the default non-zero value.
  • S4, missing from the file, retains its default value.
  • S5, specified in the file, overrides the default value.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn