Hacker News new | past | comments | ask | show | jobs | submit login

Whenever you do:

  v := interfaceType(concreteTypeValue)
in Go, what you're actually doing on a lower level is:

  dataPtr := &concreteTypeValue
  typePtr := typeData[concreteType]()
  v := interfaceData{
          data: dataPtr,
          typ: typePtr,
  }
The first line here is the allocation, since (at least, the way I recall the rule) in Go pointers never point to values on the stack, so concreteTypeValue must be allocated on the heap. The rule about pointers not pointing to the stack is there to make it easier for goroutine stacks to grow dynamically.

See https://go.dev/doc/faq#stack_or_heap.




>in Go pointers never point to values on the stack

This is only the case for pointers that the compiler can't prove not to escape:

>In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.


That could be true, but I've done a few optimizations of allocations in Go code, and I don't recall pointers to stack values ever being optimized (unless the entire branch is removed, of course). If anyone could provide an example of the code that does pointer operations yet doesn't cause allocations, I'd appreciate it!



Ah, so extremely localized uses of pointers, got it, thanks.


More or less, yes, but it doesn't have to be extremely local. Here's a variant of the example that introduces a function call boundary:

https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename...


Oops, copy paste error there. Here is the example with the function call boundary:

https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: