The difference between make and new in Go

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Make is used for memory allocations of built-in types (map, slice, and channel). New is used for various types of memory allocations.

The built-in function new is essentially the same as the function of the same name in other languages: new (T) allocates 0 of the memory space of the T type populated by the value, and returns its address, which is a value of type *t. In the terms of go, it returns a pointer to the 0 value of the newly assigned type T. One thing is very important:new Returns a pointer.


The built-in function make (T, args) has a different function than new (t), making can only create slice, map, and channel, and returns a T type with an initial value (not 0) instead of *t.

Essentially, the reason that these three types are different is that references to data structures must be initialized before they are used. For example, a slice is a three-item descriptor that contains pointers, lengths, and capacities to the data (internal array), and slice is nil until those items are initialized. For slice, map, and channel, make initializes the internal data structure and populates the appropriate values. Make returns the initialized (not 0) value.

Make is a method of referencing type initialization.

Reference: HTTPS://GITHUB.COM/ASTAXIE/BUILD-WEB-APPLICATION-WITH-GOLANG/BLOB/MASTER/02.2.MD

The above address provides a memory allocation graph for make and new corresponding to the underlying.

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.