Go語言學習之make和new的區別
阿新 • • 發佈:2020-10-27
1.new函式
在官方文件中,new函式的描述如下
// The new built-in function allocates memory. The first argument is a type, // not a value, and the value returned is a pointer to a newly // allocated zero value of that type. func new(Type) *Type
可以看到new函式只能傳遞一個引數,該引數為一個任意型別,可以是go的內建型別,也可以是你自定義的型別
那麼new函式到底做了哪些事呢.
- 分配記憶體
- 設定零值
- 返回指標(重要)
舉個例子
import "fmt" type Student struct { name string age int } func main() { // new 一個內建型別 num := new(int) fmt.Println(*num) //列印零值:0 // new 一個自定義型別 s := new(Student) s.name = "zhangsan" }
2.make函式
在官方文件中,make函式描述如下
//The make built-in function allocates and initializes an object//of type slice, map, or chan (only). Like new, the first argument is // a type, not a value. Unlike new, make's return type is the same as // the type of its argument, not a pointer to it. func make(t Type, size …IntegerType) Type
翻譯:
- 1.內建函式 make 用來為 slice,map 或 chan 型別(注意:也只能用在這三種類型上)分配記憶體和初始化一個物件
- 2.make 返回型別的本身而不是指標,而返回值也依賴於具體傳入的型別,因為這三種類型(slice,map 和 chan)本身就是引用型別,所以就沒有必要返回他們的指標了
由於這三種類型都是引用型別,所以必須得初始化(size和cap),但是不是置為零值,這個和new是不一樣的
//切片 a := make([]int, 2, 10) // 字典 b := make(map[string]int) // 通道 c := make(chan int, 10)
3.總結
new:為所有的型別分配記憶體,並初始化為零值,返回指標。
make:只能為 slice,map,chan 分配記憶體,並初始化,返回的是型別。
另外,目前來看 new 函式並不常用,大家更喜歡使用短語句宣告的方式
a := new(int) a = 1 // 等價於 a := 1
但是 make 就不一樣了,它的地位無可替代,在使用slice、map以及channel的時候,還是要使用make進行初始化,然後才可以對他們進行操作