9.Go language memory allocation mechanism make & new

Go has two mechanisms to allocate memory, the rules are simple, let's briefly explain.

1, new functions
New returns after () function can give a value type data memory allocation, call succeeds memory block pointer to an initialized, while this type is initialized to zero values, prototype definition:
FUNC new new (the Type) * the Type
new new is a built-in function to allocate memory, but unlike the work of other languages new, it's just the memory is cleared, rather than initializing memory.
2, make the function
Make () function is used to allocate memory reference types, such as: slice, map, channal other thing to note here is make () to create a reference to an object type, rather than a memory space pointer. Make () Function Prototype:
FUNC the make (Type, size IntegerType) Type
Parameter Type must be a reference type (slice, map, channal); IntegerType number parameter of the object to be created. New and different is the call to make a successful return an object instead of a pointer to a memory space.
new role is to initialize a pointer to type (* T), is initialized to make the role of slice, map and returns a reference or chan (T)

package main 

import ( 
"fmt" 
) 

func main() { 
  p := new([]int) 
  fmt.Println(p)     //输出&[],p本身是一个地址 
  s := make([]int, 1) 
  fmt.Println(s)     //输出[0],s本身是一个slice对象,其内容默认为0 
} 

As can be seen by this example, when the slice, map channel and initialized, make use of new ways better than, other forms of initialization are performed using the new

2021342-e1846468b57bb93c.png

Reproduced in: https: //www.jianshu.com/p/dc5f75a03a40

Guess you like

Origin blog.csdn.net/weixin_33755847/article/details/91334981