Home > Mobile >  What is the diff between initializing a global struct pointer vs a global struct in golang?
What is the diff between initializing a global struct pointer vs a global struct in golang?

Time:09-06

Let's say I have the following code

//var mystruct *MyStruct  // method 1
//var mystruct MyStruct   // method 2

type MyStruct struct {
   // struct fields
}

I understand the basic differences between method 1 and method 2 in terms of declaring the mystruct variable. Both of them requires allocating the same amount of memory and the first method requires an additional pointer. The first method allocates memory on heap and the second method allocates on stack. I imagine the first method is preferred if stack memory can be under pressure.

Does it have any other practical differences between these two ways of declaring a struct variable as a global variable within the package?

CodePudding user response:

Declaring a pointer does not allocate memory on the heap. It just declares a pointer.

If you declare an instance of a struct (not a pointer), then the memory for that struct is allocated on the heap, and stays there. The symbol name used to declare it (myStruct) always refers to that struct instance.

If you declare a pointer *myStruct as above, it is initialized to nil. Accessing it will panic. You have to assign myStruct to the address of an allocated instance of MyStruct. One important difference is that if you declare a pointer, where it points may change during the program.

  •  Tags:  
  • go
  • Related