The difference between new and make in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

New allocates the structure space and initializes it to zero, without further initialization
After new, a pointer is needed to point to the structure
Make allocates the structure space and its attached space, and completes the pointer initialization.
Make returns this structure space without assigning a pointer to another

Example NEW:
var p *[]int = new ([]int)
Or
P: = new ([]int)
The above allocates a slice structure, but the PTR pointer in the structure that should point to the underlying array is empty, so you cannot actually access the data in this slice
Also assigns a pointer p, which is (in 32-bit system) occupies 4 bytes and holds the address of the slice structure

Example make:
var v []int = make ([]int, 0)
V: = Make ([]int, 0)
The above assigns a slice structure, and the PTR pointer in the structure that should point to the underlying array already points to some underlying array, the underlying array should already be allocated, so this slice is already available
Note that V is the slice structure, not a pointer to slice.
The above is only an example, the general use will be clear length and capacity: V: = make ([]int, 10, 50)

Conclusion:
From the above, it is not very meaningful to allocate slice with new because there is no proper initialization and cannot be used directly
There is a space-attached structure, which is initialized with make to complete the internal pointer initialization, which can then be immediately used

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.