News for hackers. Stuff that matters.
Re:Proposal: expression to create pointer to simple types by catlifeonmars on Monday April 19, 2021 @10:41AM (#26863243)
I’m not sure I understood this correctly. Does the following allocate (on the heap)?

    foo := MyStruct{}
Re:Proposal: expression to create pointer to simple types by coder543 on Monday April 19, 2021 @11:31AM (#26863876)
No, that does not cause a heap allocation on its own. If other lines of code in that function caused a pointer to that value to escape the lifetime of the current function's stack frame, the compiler would determine that it has to be heap allocated instead.

I believe the person you are replying to was making a confusing point about some hand wavy notion of "any kind of allocation", which includes stack allocations... which are determined at compile time, not with "alloca".

Re:Proposal: expression to create pointer to simple types by catlifeonmars on Monday April 19, 2021 @01:23PM (#26865434)
Ah, that makes much more sense!
Re:Proposal: expression to create pointer to simple types by kevincox on Monday April 19, 2021 @10:46AM (#26863303)
No. In this case foo will live on the stack (unless you take its address later).

  foo := MyStruct{} // Could live on the stack
  _ := &foo // Oh, now foo must live on the heap.
Re:Proposal: expression to create pointer to simple types by coder543 on Monday April 19, 2021 @11:23AM (#26863763)
This isn't even true.

No matter what syntax you write inside a function, the Go compiler always has the final say on what is stack allocated and what is heap allocated. Taking the address of foo will not cause foo to be heap allocated unless Go is unable to prove that the pointer will live for less time than the current stack frame. Look up "escape analysis".

Basically the only way to guarantee that something will always be heap allocated is to assign it to a global variable. Even returning a pointer to that object from the current function is not a strong guarantee, since the compiler could inline this function into the caller and determine that everything can live happily inside the newly inlined stack frame without heap allocation.

Re:Proposal: expression to create pointer to simple types by kevincox on Monday April 19, 2021 @01:08PM (#26865199)
Good point. It isn't "must", I should have said "may".