Stack vs heap allocation of structs in Go, and how they relate to garbage collection

问题:

I'm new to Go and I'm experiencing a bit of cognitive dissonance between C-style stack-based programming where automatic variables live on the stack and allocated memory lives on the heap and Python-style stack-based-programming where the only thing that lives on the stack are references/pointers to objects on the heap.我是 Go 的新手,我在 C 风格的基于堆栈的编程(其中自动变量位于堆栈上,分配的内存位于堆上)和 Python 风格的基于堆栈的编程(其中唯一存在于堆栈中的是指向堆上对象的引用/指针。

As far as I can tell, the two following functions give the same output:据我所知,以下两个函数给出了相同的输出:

func myFunction() (*MyStructType, error) {
    var chunk *MyStructType = new(HeaderChunk)

    ...

    return chunk, nil
}


func myFunction() (*MyStructType, error) {
    var chunk MyStructType

    ...

    return &chunk, nil
}

ie, allocate a new struct and return it.即,分配一个新结构并返回它。

If I'd written that in C, the first one would have put an object on the heap and the second would have put it on the stack.如果我用 C 编写它,第一个将把一个对象放在堆上,第二个将把它放在堆栈上。 The first would return a pointer to the heap, the second would return a pointer to the stack, which would have evaporated by the time the function had returned, which would be a Bad Thing.第一个将返回一个指向堆的指针,第二个将返回一个指向堆栈的指针,在函数返回时它会消失,这将是一件坏事。

If I'd written it in Python (or many other modern languages except C#) example 2 would not have been possible.如果我用 Python(或除 C# 之外的许多其他现代语言)编写它,示例 2 将不可能实现。

I get that Go garbage collects both values, so both of the above forms are fine.我知道 Go 垃圾收集了这两个值,所以上述两种形式都很好。

To quote:去引用:

Note that, unlike in C, it's perfectly OK to return the address of a local variable;请注意,与 C 不同,返回局部变量的地址是完全可以的; the storage associated with the variable survives after the function returns.与变量关联的存储在函数返回后仍然存在。 In fact, taking the address of a composite literal allocates a fresh instance each time it is evaluated, so we can combine these last two lines.事实上,每次计算复合文字的地址时都会分配一个新实例,因此我们可以将最后两行组合起来。

http://golang.org/doc/effective_go.html#functions http://golang.org/doc/effective_go.html#functions

But it raises a couple of questions.但它提出了几个问题。

  1. In example 1, the struct is declared on the heap.在示例 1 中,结构体是在堆上声明的。 What about example 2?例子2呢? Is that declared on the stack in the same way it would be in C or does it go on the heap too?它是在堆栈上以与在 C 中相同的方式声明的,还是也在堆上?

  2. If example 2 is declared on the stack, how does it stay available after the function returns?如果示例 2 在堆栈上声明,它如何在函数返回后保持可用?

  3. If example 2 is actually declared on the heap, how is it that structs are passed by value rather than by reference?如果示例 2 实际上是在堆上声明的,那么结构是如何通过值而不是通过引用传递的? What's the point of pointers in this case?在这种情况下,指针的意义是什么?


解决方案:

参考一: https://en.stackoom.com/question/janD
参考二: https://stackoom.com/question/janD
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章