Go 中嵌套結構的字面初始化
在Go 中實現複雜的資料結構時,初始化巢狀結構可能是一個挑戰。在某些情況下,需要直接初始化這些結構,而不明確定義每個嵌套層級。
問題陳述
考慮以下結構:
type tokenRequest struct { auth struct { identity struct { methods []string password struct { user struct { name string domain struct { id string } password string } } } } }
初始化這個結構的天真的嘗試可能看起來像this:
req := &tokenRequest{ auth: struct { identity: struct { methods: []string{"password"}, password: { user: { name: os.Username, domain: { id: "default", }, password: os.Password, }, }, }, }, }
解決方案:命名結構類型
簡化此初始化的關鍵是使用命名結構類型。這允許您定義一次結構並在多個地方使用它:
type domain struct { id string } type user struct { name string domain domain password string } type password struct { user user } type identity struct { methods []string password password } type auth struct { identity identity } type tokenRequest struct { auth auth }
使用命名結構類型,您現在可以直接初始化tokenRequest 結構:
req := &tokenRequest{ auth: auth{ identity: identity{ methods: []string{"password"}, password: password{ user: user{ name: os.Username, domain: domain{ id: "default", }, password: os.Password, }, }, }, }, }
這提供了在Go中初始化嵌套結構體的更直接、更簡潔的方法。
以上是如何簡化 Go 中的巢狀結構初始化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文解釋了GO的軟件包導入機制:命名imports(例如導入“ fmt”)和空白導入(例如導入_ fmt; fmt;)。 命名導入使包裝內容可訪問,而空白導入僅執行t

本文解釋了Beego的NewFlash()函數,用於Web應用程序中的頁間數據傳輸。 它專注於使用newflash()在控制器之間顯示臨時消息(成功,錯誤,警告),並利用會話機制。 Lima

本文詳細介紹了MySQL查詢結果的有效轉換為GO結構切片。 它強調使用數據庫/SQL的掃描方法來最佳性能,避免手動解析。 使用DB標籤和Robus的結構現場映射的最佳實踐

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文詳細介紹了在GO中詳細介紹有效的文件,將OS.WriteFile(適用於小文件)與OS.openfile和緩衝寫入(最佳大型文件)進行比較。 它強調了使用延遲並檢查特定錯誤的可靠錯誤處理。

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器