Let's talk about the difference between the new and make keywords in Go language

PHPz
Release: 2023-03-27 17:16:36
forward
829 people have browsed it

This article will introduce a very common interview question. How common is it? This may be the starting point for many interviews. That's the difference between the two built-in functions new and make.

Let's talk about the difference between the new and make keywords in Go language

In fact, the problem itself is not complicated. To put it simply, new only allocates memory, and make can only be used to initialize slice, map and chan. Let’s talk about Let’s introduce it in detail.

new

new is a built-in function that allocates a memory and returns a pointer to that memory.

The function signature is as follows:

Source code

// 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
Copy after login

As can be seen from the above code, the new function only accepts one parameter, which is a type, and returns a pointer to the memory address of that type.

At the same time, the new function will set the allocated memory to zero, which is the zero value of the type.

Use

Use the new function to allocate memory space for variables:

p1 := new(int)
fmt.Printf("p1 --> %#v \n ", p1) //(*int)(0xc42000e250) 
fmt.Printf("p1 point to --> %#v \n ", *p1) //0

var p2 *int
i := 0
p2 = &i
fmt.Printf("p2 --> %#v \n ", p2) //(*int)(0xc42000e278) 
fmt.Printf("p2 point to --> %#v \n ", *p2) //0
Copy after login

The above code is equivalent, new(int) Initialize the allocated space to the zero value of int, that is, 0, and return the pointer of int. This has the same effect as directly declaring the pointer and initializing it.

Of course, the new function can not only allocate space for the system's default data type, but custom types can also use the new function to allocate space, as shown below:

type Student struct {
   name string
   age int
}
var s *Student
s = new(Student) //分配空间
s.name = "zhangsan"
fmt.Println(s)
Copy after login

This is the new function, which What is returned is always a pointer of the type, which points to the memory address of the allocated type. It should be noted that the new function will only allocate memory space, but will not initialize the memory space.

make

#make is also used for memory allocation, but unlike new, it is only used for memory creation of slice, map and chan, and the type it returns It's the three types themselves, not their pointer types. Because these three types are reference types themselves, there is no need to return their pointers.

The function signature is as follows:

Source code

// 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
Copy after login

It can be seen from the above code that the t parameters of the make function must It is one of slice, map and chan, and the return value is also the type itself.

Use

The following uses slice to give an example:

var s1 []int
if s1 == nil {
    fmt.Printf("s1 is nil --> %#v \n ", s1) // []int(nil)
}

s2 := make([]int, 3)
if s2 == nil {
    fmt.Printf("s2 is nil --> %#v \n ", s2)
} else {
    fmt.Printf("s2 is not nill --> %#v \n ", s2)// []int{0, 0, 0}
}
Copy after login

The zero value of slice is nil, but use make After initialization, the slice content is filled with zero values ​​of type int, such as: []int{0, 0, 0}.

map and chan are similar, so I won’t go into details.

Summary

Through the above analysis, the main differences between new and make are summarized as follows:

  • make can only be used for distribution And initialized data of type slice, map and chan. new can allocate any type of data;

  • new allocation returns a pointer, which is the type *Type. make returns the type itself, i.e. Type;

  • new The allocated space is cleared. After make allocates space, it will be initialized;

Recommended learning: "go video tutorial"

The above is the detailed content of Let's talk about the difference between the new and make keywords in Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template