【发布时间】:2020-01-30 07:19:50
【问题描述】:
我最近在学习 Golang。我知道指针和值接收器的一般工作原理。
当Unmarshal JSON string like下面2个例子时,我觉得第一个(指针接收器)更有效地使用内存。但是我看到很多例子和文章没有使用这种方式。这有什么原因吗?它们的用例是什么?
package main
import (
"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 main
import (
"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}
更新:我的效率的意思是“有效地使用内存”
【问题讨论】:
-
这与效率无关,它是关于区分JSON中是否存在值。
-
@Volker 谢谢你的回答,我明白了。 Leon 在重复的问题上解释了它为什么效率不高。
标签: go