go - What is the difference between new and make? -
new not initialize memory, zeros it. returns pointer newly allocated 0 value.
make creates slices, maps, , channels only, , returns them initialized.
what "initialized" mean in context? other differences there between new , make?
as mentioned in making slices, maps , channels:
the built-in function make takes type
t, must slice, map or channel type, optionally followed type-specific list of expressions.
it returns value of typet(not*t).
memory initialized described in section on initial values.
for instance, slice type
make([]t, length, capacity) produces same slice allocating array , slicing it, these 2 expressions equivalent:
make([]int, 50, 100) new([100]int)[0:50] so here, make creates slice, , initialize content depending on 0 value if type used (here int, '0')
you can see more need of keeping new , make separate in go: why make() or new()?
dave cheney wrote article: "go has both make , new functions, gives ?"
although
makecreates genericslice,map, ,channelvalues, still just regular values; make not return pointer values.if
newremoved in favourmake, how construct pointer initialised value ?using
newconstruct pointerslice,map, orchannelzero value works today , consistent behaviour ofnew.for confusion may cause,
make,newconsistent;
makemakes slices, maps, , channels,newreturns pointers initialised memory.
Comments
Post a Comment