go - 解码为指针与值接收器字段

标签 go

这个问题在这里已经有了答案:





Difference using pointer in struct fields

(4 个回答)


2年前关闭。




我最近在学习 Golang。我知道指针和值接收器通常是如何工作的。

当 Unmarshal JSON string like following 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}

更新:我对效率的含义是“使用内存的有效方式”

最佳答案

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

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

关于go - 解码为指针与值接收器字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59980886/

相关文章:

bash - 鱼壳中的多个 GOPATH

go - 在Kubernetes中自定义自动缩放策略

linux - 设置 Go 进行交叉编译时出错

go - 如何使用基准时间值(value)

Golang - 在结构中使用 chan slice

go - Go 中 t-digest 数据结构的线程安全实现?

regex - Go 正则表达式中的否定前瞻

go - main func 上的 reviced channel error 但是 goroutine 中的 if reviced progrenn 没有错误

go - 雨果没有按修改日期排序帖子

Golang 错误的http请求头