The difference between new of and make of in Go

  • 2020-05-10 18:21:09
  • OfStack

An overview of the

new and make 1 are two of the most confusing things for beginners in Go. But it's easy to explain the difference.

Key features of new

First new is built-in functions, you can start your http: / / golang org/pkg/builtin / # new see it here, its definition is simple:


func new(Type) *Type

The official documentation describes it as:


Built-in functions new Used to allocate memory, it's the first 1 A parameter is 1 Types. No 1 And its return value is 1 A pointer to the zero value of the new assignment type

According to this description, we can implement a function similar to new by ourselves:


func newInt() *int {
  var i int
  return &i
} someInt := newInt()

The function of this function is exactly the same as someInt := new(int). So when we define our own new functions, by convention we should also return Pointers of type.

Key features of make

make is also a built-in functions, you can start your http: / / golang org/pkg/builtin / # make see it here, the definition of it more than the new one parameter, the return value is different:


func make(Type, size IntegerType) Type

The official documentation describes it as:

NaJianHanShu make YongLaiWei slice,map or chan 类型分配内存和初始化1个对象(注意:只能用在这3种类型上),跟 new 类似,第1个参数也是1个类型而不是1个值,跟 new 不同的是,make 返回类型的引用而不是指针,而返回值也依赖于具体传入的类型,具体说明如下:


Slice: The first 2 A parameter size It specifies its length, and its capacity is the same as its length.
You can pass in no 3 To specify different capacity values, but must not be smaller than the length value.
Such as make([]int, 0, 10) Map: According to the size Size to initialize allocated memory, but after allocation map Length of 0 If the size If it is ignored, it will be allocated when initializing the allocated memory 1 A small size of memory Channel: The pipeline buffer is initialized based on the buffer capacity. If the capacity is 0 Or ignore the capacity, the pipeline has no buffer

conclusion

new initializes a pointer to a type (*T), and make initializes and returns a reference (T) for slice, map, or chan.


Related articles: