make和new都是用來分配記憶體的,相比make,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接收一個引數,可以是任意型別,回傳的是該型別的指標,輸出看下
func main() {
a := new([]int)
fmt.Printf("%T %p\n", a, a)
}
結果:
*[]int 0xc000004480
a的型別是我們傳入的 []int 型別的指標 *[]int
0xc000004480是該指標的地址
不會進行初始化,new完的map不能直接使用,會panic
new會將型別置為零值
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. 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
看函式的原型,第一個引數是型別,看注釋,型別僅支持 map、slice、channel,
第二個引數是大小,
func main() {
//a := new([]int)
//fmt.Printf("%T %p\n", a, a)
var a map[int]int
a = make(map[int]int, 8)
var b []int
b = make([]int, 8)
fmt.Println(len(b), cap(b), b)
fmt.Printf("%T %v %v\n", a, a, len(a))
c := make(chan int,5)
fmt.Println(c, len(c))
}
結果
map[int]int map[] 0
8 8 [0 0 0 0 0 0 0 0]
0xc000076000 0
初始化完成后,型別是傳入型別對應的一個實體,
對于第二個引數 size,對于slice,傳入的引數初始化完成后引數對應的是切片的 len和cap 均為size,并且切片中得值初始化為零值
對于map,size為 map 的大小
對于channel,不指定size的,表示該channel為無緩沖的channel,指定了大小的,表示該channel 為有緩沖的channel
總結
make僅僅能用于初始化 map、slice、channel,而且對于map和channel,必須初始化之后才能使用否則會報錯
map未初始化
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
channel 未初始化
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.main()
new 僅僅是為對應型別申請一片記憶體空間,然后回傳該記憶體對應的指標
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/265989.html
標籤:區塊鏈
上一篇:最簡單的以太坊(ETH)挖礦教程
