make和new關鍵字的區別及實現原


new 和 make 是兩個內置函數,主要用來創建並分配類型的內存。在我們定義變量的時候,可能會覺得有點迷惑,不知道應該使用哪個函數來聲明變量,其實他們的規則很簡單,

new 只分配內存,

make 只能用於 slice、map 和 channel 的初始化,

下面我們就來具體介紹一下:

new

在Go語言中,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 函數只接受一個參數,這個參數是一個類型,並且返回一個指向該類型內存地址的指針。同時 new 函數會把分配的內存置為零,也就是類型的零值。

【示例】使用 new 函數為變量分配內存空間。
var sum *int
sum = new(int) //分配空間
*sum = 98
fmt.Println(*sum)
當然,new 函數不僅僅能夠為系統默認的數據類型,分配空間,自定義類型也可以使用 new 函數來分配空間,如下所示:
type Student struct {
name string
age int
}
var s *Student
s = new(Student) //分配空間
s.name ="dequan"
fmt.Println(s)
這里如果我們不使用 new 函數為自定義類型分配空間(將第 7 行注釋),就會報錯:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x80bd277]
goroutine 1 [running]:
這就是 new 函數,它返回的永遠是類型的指針,指針指向分配類型的內存地址。

make

make 也是用於內存分配的,但是和 new 不同,它只用於 chan、map 以及 slice 的內存創建,而且它返回的類型就是這三個類型本身,而不是他們的指針類型,因為這三種類型就是引用類型,所以就沒有必要返回他們的指針了。

在Go語言中,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. 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, so make([]int, 0, 10) allocates a slice of length 0 and
// capacity 10.
// 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
通過上面的代碼可以看出 make 函數的 t 參數必須是 chan(通道)、map(字典)、slice(切片)中的一個,並且返回值也是類型本身。

注意:make 函數只用於 map,slice 和 channel,並且不返回指針。如果想要獲得一個顯式的指針,可以使用 new 函數進行分配,或者顯式地使用一個變量的地址。

Go語言中的 new 和 make 主要區別如下:
  • make 只能用來分配及初始化類型為 slice、map、chan 的數據。new 可以分配任意類型的數據;
  • new 分配返回的是指針,即類型 *Type。make 返回引用,即 Type;
  • new 分配的空間被清零。make 分配空間后,會進行初始化;

總結

最后,簡單總結一下Go語言中 make 和 new 關鍵字的實現原理,make 關鍵字的主要作用是創建 slice、map 和 Channel 等內置的數據結構,而 new 的主要作用是為類型申請一片內存空間,並返回指向這片內存的指針。
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM