Go language learning Path five: Go language memory allocation mechanism make&new

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

Go has two mechanisms for allocating memory, the rules are simple, here is a brief introduction.
1. New function
The New () function can allocate memory for data of a value type (not knowing what value type goes to the section of the slice), and returns an initialized memory block pointer when the call succeeds, and the type is initialized to a value of 0, the prototype defines:
Func new (type) * type
New is a built-in function that allocates memory, but unlike the work done by new in other languages, it simply zeroed out the memory instead of initializing it.
2. Make function
The make () function is used to allocate memory space for reference types, such as: slice,map,channal, and so on, it is important to note that make () creates an object of reference type, not a pointer to a memory space. Make () function prototype:
Func make (type,size integertype) Type
The parameter type must be a reference type (slice,map,channal), and the parameter integertype specifies the number of objects to be created. Unlike new, make call success is a pointer that returns an object instead of a memory space.
The role of new is to initialize a pointer to a type (*T), which is initialized for Slice,map or Chan and returns a reference (T)
Package Main

Import (
"FMT"
)

Func Main () {
P: = new ([]int)
Fmt. PRINTLN (p)//output &[],p itself is an address
S: = make ([]int, 1)
Fmt. PRINTLN (s)//output [0],s itself is a slice object whose content defaults to 0
}
This example shows that when initializing the Slice,map and channel, using make is better than the new method, while the other forms are initialized with new.

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.