explictly call make new cause space in heap?

65 views
Skip to first unread message

xie cui

unread,
Jan 29, 2021, 12:09:58 PM1/29/21
to golang-nuts
when i call make new explictly, does it mean the space must be in heap, in my mind, it still has chance to alloc in stack in some situation?
my question is is it must be in heap, or in some case it can alloc in stack?

Ian Lance Taylor

unread,
Jan 29, 2021, 1:00:05 PM1/29/21
to xie cui, golang-nuts
On Fri, Jan 29, 2021 at 9:10 AM xie cui <cuiw...@gmail.com> wrote:
>
> when i call make new explictly, does it mean the space must be in heap, in my mind, it still has chance to alloc in stack in some situation?
> my question is is it must be in heap, or in some case it can alloc in stack?

The builtin function new can return the address of a stack value in some cases.

Writing
p := new(T)
is approximately the same as writing
var unnamedVariable T
p := &unnamedVariable

Whether the new variable is created on the stack or the heap depends
on the compiler's escape analysis of p.

Ian
Reply all
Reply to author
Forward
0 new messages