首頁  >  文章  >  後端開發  >  以下是一些標題選項,請記住問題格式的需要: * **為什麼 Go 中 `json.Unmarshal` 回傳 Map 而不是結構體? **(簡單直接) * **Golang:解組 int

以下是一些標題選項,請記住問題格式的需要: * **為什麼 Go 中 `json.Unmarshal` 回傳 Map 而不是結構體? **(簡單直接) * **Golang:解組 int

DDD
DDD原創
2024-10-26 02:44:02325瀏覽

Here are a few title options, keeping in mind the need for a question format:

* **Why Does `json.Unmarshal` Return a Map Instead of a  Struct in Go?** (Simple and direct)
* **Golang: Unmarshaling into an Interface - Why is My Struct a Map?** (More specif

為什麼 json.Unmarshal 回傳一個映射而不是預期的結構?

在這個Playground 範例中,json.Unmarshal 傳回一個映射而不是預期的結構:http ://play.golang.org/p/dWku6SPqj5.

出現此問題的原因是,interface{} 參數被傳遞給json.Unmarshal,並且庫嘗試將其解組為位元組數組。然而,該函式庫沒有直接引用相應的結構體,儘管它有一個reflect.Type引用。

問題出在下面的程式碼:

<code class="go">var ping interface{} = Ping{}
deserialize([]byte(`{"id":42}`), &ping)
fmt.Println("DONE:", ping) // It's a simple map now, not a Ping. Why?</code>

To解決此問題,要麼將指標作為抽象介面明確傳遞給Ping 結構:

<code class="go">var ping interface{} = &Ping{}
deserialize([]byte(`{"id":42}`), ping)
fmt.Println("DONE:", ping)</code>

或者,如果直接指針不可用,請使用反射建立新指針,反序列化到其中,然後複製返回值:

<code class="go">var ping interface{} = Ping{}
nptr := reflect.New(reflect.TypeOf(ping))
deserialize([]byte(`{"id":42}`), nptr.Interface())
ping = nptr.Interface()
fmt.Println("DONE:", ping)</code>

以上是以下是一些標題選項,請記住問題格式的需要: * **為什麼 Go 中 `json.Unmarshal` 回傳 Map 而不是結構體? **(簡單直接) * **Golang:解組 int的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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