-1

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Athfan
  • 125
  • 8
  • Does this answer your question? [Stack vs heap allocation of structs in Go, and how they relate to garbage collection](https://stackoverflow.com/questions/10866195/stack-vs-heap-allocation-of-structs-in-go-and-how-they-relate-to-garbage-collec) – Erwin Bolwidt Sep 11 '22 at 05:11
  • 3
    „In memory“. That’s all to know here. Neither the language specification nor encoding/json make any guaranties except the the data _is_ stored. – Volker Sep 11 '22 at 11:18
  • @ErwinBolwidt I guess it's a bit different concept. It was very informative ty. But I think memcpy's answer makes a lot of sense to my question. I'll accept it – Athfan Sep 11 '22 at 14:36

1 Answers1

2

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.

memcpy
  • 36
  • 2
  • "The reflect.New function calls a private runtime function to allocate memory" Is this allocated memory temporary? like it's a stack level thing or heap level thing? – Athfan Sep 11 '22 at 14:39
  • 1
    It's a heap thing, but that distinction is not important unless you are optimizing allocations. The important thing is that the memory allocation has a lifetime equal to or greater than any references to the memory. – memcpy Sep 11 '22 at 17:37