我最近在學習 Golang。我知道指針和值接收器通常是如何工作的。當 Unmarshal JSON string like following 2示例時,我覺得第一個(指針接收器)更有效地使用內存。但是我看到很多例子和文章沒有使用這種方式。這有什么原因嗎?它們的用例是什么?package mainimport ( "encoding/json" "fmt")type Outer struct { ID int `json:"id"` PointerValue *string `json:"pointer_str"` Inner *Inner `json:"inner"`}type Inner struct { Value string `json:"value"`}func main() { testJson := `{ "id": 1, "pointer_str": "example-value", "inner": { "value": "some-value" } }` testStruct := &Outer{} json.Unmarshal([]byte(testJson), testStruct) fmt.Printf("%+v\n", testStruct) fmt.Printf("%+v\n", *testStruct.PointerValue) fmt.Printf("%+v\n", testStruct.Inner)}輸出:&{ID:1 PointerValue:0x40c250 Inner:0x40c258}example-value&{Value:some-value}或者package mainimport ( "encoding/json" "fmt")type Outer struct { ID int `json:"id"` PointerValue string `json:"pointer_str"` Inner Inner `json:"inner"`}type Inner struct { Value string `json:"value"`}func main() { testJson := `{ "id": 1, "pointer_str": "example-value", "inner": { "value": "some-value" } }` testStruct := &Outer{} json.Unmarshal([]byte(testJson), testStruct) fmt.Printf("%+v\n", testStruct) fmt.Printf("%+v\n", testStruct.Inner)}輸出:&{ID:1 PointerValue:example-value Inner:{Value:some-value}}{Value:some-value}更新:我對效率的含義是“使用內存的有效方式”
1 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
認為它更有效的假設是錯誤的。沒有指針的那個效率更高,因為不需要間接,并且該值與 的其他值一起在內存緩存中Outer
。訪問會更快。
當內部值是可選的時使用指針。nil
當該值不存在時,它將具有一個值。否則使用沒有指針的表格。如果 JSON 字符串中的 Inner 的值可能是 ,您也可以使用指針null
。
- 1 回答
- 0 關注
- 136 瀏覽
添加回答
舉報
0/150
提交
取消