The difference between make and new in golang

The difference between make and new in golang

new function

The description of the new official document:

// 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

Summarize:

  1. new is a built-in function used to allocate internal dimensions for various built-in types. These built-in types can be arbitrary, and you can also new your custom struct type.
  2. Allocates a memory for a zero value of the corresponding type.
  3. The new function returns a pointer.

example

type Person struct {
    
    
   name string
   age int
}

func main() {
    
    
    // new 一个任意的内建类型
    num := new(int)
    fmt.Println(*num) //打印值,是默认的零值

    // new 一个自行定义的结构体类型
    s := new(Person)
    s.name = "张三"
}

make function

The official documentation of make describes:

//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.

func make(t Type, size ...IntegerType) Type

Summarize:

  1. The make function can only be used for three types of creation - slice, map, and chan types. The built-in function allocates memory and initializes an object for it.
  2. What make returns is the type itself, not a pointer. The type of the returned value depends on the value you want to create, because the types mentioned in ① are all reference types, so there is no need to return a pointer type in essence.
  3. These three types are reference types, so instead of assigning a value of 0 to them, we initialize them. For slice, the second parameter of make represents the length of the slice, so it must be assigned.

example

//切片
a := make([]int, 20, 100)

// 字典
b := make(map[string]int)

// 通道
c := make(chan int, 5)

Summarize

new function: allocates memory for all types, initializes it to a zero value, and returns a pointer.

make function: can only allocate and initialize memory for slice, map, and chan, and return the type.

In addition, the new function is not commonly used, and everyone prefers to use short statement declarations instead of declaring variables with new.

Thinking: Can new be used instead of make to create?

Answer: Yes.

func main() {
    
    
	a := *new([]int)
	fmt.Printf("%T, %v\n", a, a==nil)

	b := *new(map[string]int)
	fmt.Printf("%T, %v\n", b, b==nil)

	c := *new(chan int)
	fmt.Printf("%T, %v\n", c, c==nil)
}

Author: Chen Shuangyin

Guess you like

Origin blog.csdn.net/ekcchina/article/details/131130140