当指针被用作结构体字段时,底层值实际上存储在哪里?

huangapple go评论89阅读模式
英文:

When pointers are used in a struct field, where is the underlying value actually stored?

问题

举个例子,我们来看一下这个结构体:

var input struct {
    Title   *string         `json:"title"`
    Year    *int32          `json:"year"`
    Runtime *data.Runtime   `json:"runtime"`
    Genres  []string        `json:"genres"`
}

我理解在解码 JSON 值时使用指针值的目的。但我的问题是,当我们将一个指向字符串的指针存储在输入字段中(例如 input.Title),该指针的底层值存储在哪里?它只是随机存储在某个内存地址中吗?或者背后实际上发生了什么?

英文:

For an example, let's take this struct

var input struct {
Title *string `json:"title"`
Year *int32 `json:"year"`
Runtime *data.Runtime `json:"runtime"`
Genres []string `json:"genres"`
}

I get the purpose of using pointer values like this when decoding JSON values. But my question is when we store a pointer to a string in the input field (for an ex) input.Title, Where does the underlying value for that pointer is stored? It's simply stored in some memory address randomly? or what actually is going on behind the scenes

答案1

得分: 2

JSON解码器调用reflect.New来获取一个指向新的空字符串值的指针。解码器将该值设置为解码后的字符串,并将结构字段设置为该指针。

reflect.New函数调用一个私有的运行时函数来为该值分配堆内存。该函数返回指向该内存的指针。

英文:

The JSON decoder calls reflect.New to get a pointer to a new empty string value. The decoder sets the value to the decoded string and sets the struct field to the pointer.

The reflect.New function calls a private runtime function to allocate heap memory for the value. The function returns a pointer to that memory.

huangapple
  • 本文由 发表于 2022年9月11日 10:08:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/73676361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定