Home >Backend Development >Golang >How to Efficiently Merge Go Structs While Prioritizing Specific Values?

How to Efficiently Merge Go Structs While Prioritizing Specific Values?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 21:03:10412browse

How to Efficiently Merge Go Structs While Prioritizing Specific Values?

Merging Struct Fields Efficiently

Problem

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.

Reflection-Based Solution

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.

Encoding/JSON-Based Solution

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:

  • Missing values in config.json will retain the default values.
  • Values in config.json will override default values, even if they are set to zero.
  • Explicit zero values in config.json will overwrite non-zero default values.

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!

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