1. 程式人生 > >golang new make 區別

golang new make 區別

del res mce ike IT read ola div chapter

make用於內建類型(map、slice 和channel)的內存分配

new用於各種類型的內存分配

new(T)分配了零值填充的T類型的內存空間, 並且返回其地址,即一個*T類型的值

內建函數make(T, args)與new(T)有著不同的功能,
make只能創建slice、map和channel,
並且返回一個有初始值(非零)的T類型,而不是*T

本質來講,導致這三個類型有所不同的原因是指向數據結構的引用在使用前必須被初始化

The way to go

new(T) allocates zeroed storage for a new item of type T and returns its address,


a value of type *T:

   it returns a pointer to a newly allocated zero value of type T,

ready for use;

it applies to value types like arrays and structs (see Chapter 10);
it is equivalent to &T{ }


make(T) returns an initialized value of type T;
  it applies only to the 3 built-in reference types:


slices, maps and channels (see chapters 8 and 13).

技術分享圖片

golang new make 區別