You must be familiar with new and make, but when to use new and when to use make, perhaps many new developers do not understand, this article will briefly note the differences between new and make and the timing of their use.
Using the new keyword
Go provides two ways to allocate memory, one is new and the other is make. These two keywords do different things and have different types of applications, which may cause some confusion for those who are just starting out, but the rules for using these two keywords are very simple. new(T) declares that it will directly get the storage location and configure Zero Value (initialization), that is, the numeric type is 0 and the string type is "". At the bottom is the example program.
After running, you can see the following result.
The above practice is less used, more people use it on struct, because of the feature of new, it can be used directly on struct to do initialization, here is the sample program.
As you can see above, initialization is quickly achieved through new, but one inconvenience is that if the developer wants to plug in a specific initialization value, there is no way to do it through new, so most of the writing will be changed to the following, example link.
|
|
Or most of them will write a new Func to do the initialization settings, example program as follows.
|
|
However, if new is used on slice, map and channel, its initial value will be nil, see the following example.
The result is panic.
The initialization of map will result in a nil, so usually when declaring slice, map and channel, another declaration method provided by Go, make, is used.
Using make keywords
The difference between make and new is that new returns a pointer, while make does not. make is usually only used to declare three places, slice, map and channel, if you really want to get a pointer, it is recommended to use new. The following is map as an example
|
|
The above example shows that p is declared as a map pointer, and after new initializes the map, it needs to be written as map[string]string{} independently to work properly. Usually, I rarely use new in my own development, instead, I use make when declaring slice, map and channel. Remember, make will not return a pointer, so if you really want to get a pointer, use new, but the code will be more complicated.
Summary
To summarize the difference between make and new
makecan allocate and initialize the required memory space and structure, whilenewcan only return the pointer location.makecan only be used in three typesslice,mapandchannelmakecan initialize the length and capacity of the above three formats to provide efficiency and reduce overhead