Golang 中 new 和 make的區別

Golang 內置兩個函數,new 和 make ,其做用都是用來分配內存的。這麼說可能會形成混淆,但其實規則很簡單,其實他們適用於不一樣的類型。git

  • make 函數只用於給 slice、map、channel進行初始化;
  • new 函數參數爲 一個類型不是一個值,用該類型的零值初始化一塊空間,並返回該空間的指針。

咱們看一下下面的案例:github

package main

import (
	"fmt"
)

func main() {
	var i *int

	*i=10
	fmt.Println(*i)

}
複製代碼

運行報錯,panic: runtime error: invalid memory address or nil pointer dereference。錯誤很明顯提示無效的內存地址或者空指針錯誤。
如何解決呢,很簡單,咱們只須要使用new來進行內存分配。bash

package main

import (
	"fmt"
)

func main() {
	var i *int
	i = new(int)
	*i = 10
	fmt.Println(*i)

}
複製代碼

再次運行,完美輸出結果 10 。
咱們再經過源碼看看new 函數ide

// 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
複製代碼

只接收一個參數(type),而且返回了一個初始化爲零值的內存指針。函數

再看看 make 函數ui

// 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. The specification of the result depends on // the type: // Slice: The size specifies the length. The capacity of the slice is // equal to its length. A second integer argument may be provided to // specify a different capacity; it must be no smaller than the // length. For example, make([]int, 0, 10) allocates an underlying array // of size 10 and returns a slice of length 0 and capacity 10 that is // backed by this underlying array. // Map: An empty map is allocated with enough space to hold the // specified number of elements. The size may be omitted, in which case // a small starting size is allocated. // Channel: The channel's buffer is initialized with the specified
//	buffer capacity. If zero, or the size is omitted, the channel is
//	unbuffered.
func make(t Type, size ...IntegerType) Type
複製代碼
  • 只爲 slice, map, or chan (only)分配內存和初始化;
  • 和 new 函數同樣的是第一個參數是一個 type 不是 value;
  • 和 new 函數不一樣的是make 返回的不是指針,返回的是參數中傳遞進來的類型自己;

你確定會困惑,爲何make 不返回指針呢,由於slice, map, or chan自己就是引用類型。具體能夠查看文章深刻理解 Slicethis

更多內容,歡迎關注個人Githubspa

相關文章
相關標籤/搜索