」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何高效合併相同類型的Go結構體? JSON編碼法

如何高效合併相同類型的Go結構體? JSON編碼法

發佈於2025-04-16
瀏覽:995

How Can I Efficiently Merge Go Structs of the Same Type Using JSON Encoding?
在GO編程領域中合併了相同結構的字段與JSON編碼

,這是同一類型的兩個結構的任務,經常出現。考慮一個場景,其中您具有默認配置,例如:

類型config struct { 路徑字符串 ID字符串 鍵字符串 ADDR字符串 大小UINT64 } var DefaultConfig = Config{"", "", "", "", 0}And a configuration loaded from a file, such as:

var FileConfig = Config{"", "file_id", "", "file_addr", 0}

type Config struct {
  path string
  id   string
  key  string
  addr string
  size uint64
}

var DefaultConfig = Config{"", "", "", "", 0}

最初,您可以利用此任務的反射來思考:

b:= reflect.valueof(默認).elem() o:=反射。 valueof(file).elem() 對於我:= 0; i var FileConfig = Config{"", "file_id", "", "file_addr", 0}編碼/JSON軟件包提供了一種簡單的機制,可以將JSON數據放入預定義的GO結構中。利用此技術,您可以優雅地合併配置:

import( “編碼/JSON” “弦” ) const filecontent =`{“ id”:“ file_id”,“ addr”:“ file_addr”,“ size”:100}`: func umarshalconfig(conf *config,content string)錯誤{ 返回json.newdecoder(strings.newreader(content))。解碼(conf) } func mergeconfigs(defconfig *config,fileconfig *config)錯誤{ 如果err:= umarshalconfig(defconfig,filecontent); err! = nil { 返回錯誤 } 對於_,v:= range fileconfig { defconfig [v.key] = v.value } 返回無 }

在此解決方案中,FileConfig未貼在默認配置中。編碼/JSON軟件包處理設置字段值的所有復雜性,包括缺失值(默認值為其零值)和文件指定的值,這些值覆蓋了默認值。

通過使用UnmarShaling,您可以利用簡單有效的解決方案來確保與Fileconfig字段相同的合併結構,從而使該fieconfig字段均可為fileconfig offig five five five Inde Is Is Inde Is Is Inde Is Is Inde Indive [

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3