首頁 >後端開發 >Golang >如何在 Golang 中正確初始化巢狀結構?

如何在 Golang 中正確初始化巢狀結構?

Barbara Streisand
Barbara Streisand原創
2024-12-22 02:41:12381瀏覽

How to Properly Initialize Nested Structs in Golang?

Golang 中的巢狀結構初始化

在 Golang 中使用巢狀結構時,初始化主結構可能會很棘手。本指南旨在為嘗試使用嵌入的匿名結構體作為欄位來初始化結構體時遇到的錯誤提供解決方案。

遇到錯誤

type DetailsFilter struct {
  Filter struct {
    Name    string
    ID      int
  }
}

var M map[string]interface{}
M = make(map[string]interface{})
M["Filter"] = map[string]interface{}{"Name": "XYZ", "ID": 5}
var detailsFilter = DetailsFilter{Filter: M["Filter"]}}

此程式碼嘗試初始化DetailsFilter具有巢狀匿名結構 Filter 的結構。但是,當嘗試從映射中初始化 Filter 欄位時,會遇到錯誤:

can not use (type interface {}) as type struct in field value : need type assertion

解決方案

建議的解決方案是避免在構造期間初始化巢狀匿名結構。相反,初始化零值結構,然後將值分配給巢狀欄位:

df := DetailsFilter{}
df.Filter.Name = "myname"
df.Filter.ID = 123

另一種選擇是命名匿名結構類型並明確初始化它:

type Filter struct {
    Name string
    ID   int
}

type DetailsFilter struct {
    Filter Filter
}

df := DetailsFilter{Filter: Filter{Name: "myname", ID: 123}}

其他注意

  • 遇到的錯誤是因為map包含一個interface{}值,不能直接賦值給struct欄位。
  • 命名匿名結構類型可以進行更明確的初始化。
  • 使用巢狀結構時,了解不同初始化方法的限制非常重要。

以上是如何在 Golang 中正確初始化巢狀結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn