[英]what does make and new actually do?
在Go中,如果要創建T對象,可以嘗試以下方法:
t := T{}
// t是在當前堆棧中創建的實際對象
p := &T{}
// p是指向當前堆棧中創建的實際對象的指針
p := make(T)
// p是指向在堆中創建的實際對象的指針
p := new(T)
// p是指向在堆中創建的實際對象的指針
我想知道我的評論是否正確?
t := T{} // t is the actual object created in the current stack
p := &T{} // p is a pointer points to the actual object which is created in the current stack
p := make(T) // p is a pointer points to the actual object which is created in the heap
p := new(T) // p is a pointer points to the actual object which is created in the heap
我想知道我的評論是否正確?
不完全是,對象是分配在堆棧上還是堆上取決於逃逸分析,而不是用於實例化該對象的特定符號,實際上Dave也為此寫了一些東西 。
查看結果的類型是有啟發性的。
make(T, ...)
返回類型T
make
僅可用於一些內置類型(切片,地圖,通道)。 對於這些類型,它基本上是“構造函數”。 new(T)
返回類型*T
它適用於所有類型,並且對所有類型都具有相同的作用-它返回一個指向T
的新實例(其值為零)的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.