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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章