在golang中,初始化全局结构指针和初始化全局结构体之间有什么区别?

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

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

问题

让我们假设我有以下的代码:

//var mystruct *MyStruct  // 方法1
//var mystruct MyStruct   // 方法2

type MyStruct struct {
   // 结构体字段
}

我理解方法1和方法2在声明mystruct变量方面的基本区别。它们都需要分配相同数量的内存,而第一种方法需要额外的指针。第一种方法在堆上分配内存,而第二种方法在栈上分配内存。我想象如果栈内存可能会受到压力,第一种方法可能更受欢迎。

在包内将结构体变量声明为全局变量时,它们是否有其他实际区别呢?

英文:

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?

答案1

得分: 3

声明指针并不会在堆上分配内存,它只是声明了一个指针。

如果你声明一个结构体的实例(而不是指针),那么该结构体的内存将在堆上分配,并且保持在那里。用于声明它的符号名(myStruct)始终指向该结构体实例。

如果你像上面那样声明一个指针 *myStruct,它会被初始化为 nil。访问它将导致恐慌。你必须将 myStruct 赋值为分配的 MyStruct 实例的地址。一个重要的区别是,如果你声明一个指针,它指向的位置可能会在程序运行期间发生变化。

英文:

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.

huangapple
  • 本文由 发表于 2022年9月6日 13:04:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/73616919.html
匿名

发表评论

匿名网友

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

确定