英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论