【问题标题】:Unmarshal into pointer vs value receiver feilds [duplicate]解组为指针与值接收器字段[重复]
【发布时间】: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


【解决方案1】:

认为它更有效的假设是错误的。没有指针的那个效率更高,因为不需要间接并且该值与Outer 的其他值一起在内存缓存中。访问会更快。

当内部值是可选的时使用指针。当值不存在时,它将具有nil 值。否则使用没有指针的表格。如果 JSON 字符串中的 Inner 的值可能是 null,您也可以使用指针。

【讨论】:

  • 感谢您的回答,似乎是重复的问题。但是,您的回答足以理解它。
猜你喜欢
  • 2017-11-30
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多