New and make differences in Golang

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

There are two memory allocation mechanisms in Golang: New and make, which differ significantly from each other.

NEW: Used to initialize an object and return the first address of the object. itself is a pointer. Can be used to initialize any type

Make: Returns an initialized instance, returning an instance, not a pointer, which can only be initialized: Slice,map and channel three types

    1. Package Main
    2. Import (
    3. "FMT"
    4. )
    5. Func Main () {
    6. A : = new ([]int)
    7. Fmt. Println (a)//output &[],a itself is an address
    8. b : = Make ([]int, 1)
    9. Fmt. PRINTLN (b)//output [0],b itself is a slice object whose content defaults to 0
    10. }

This example shows that when initializing Slice,map and channel, using make is better than new, while other forms are initialized with new.

Initialization

Initialization with new can only be done by default initialization and cannot be assigned a value. Many times, default initialization is not a good idea, such as a struct, the default value of the structure of the initialization is not much use, so in the face of struct initialization we generally apply the following methods:

    1. Type Rect struct {
    2. X, y float64
    3. width, height float64
    4. }

So we initialize the struct by adding the address symbol in front of the struct:

    1. Rect3 : = &rect{0, 0, .
    2. Rect4 : = &rect{width:100, height:200}

This initialization method is very common in initializing structs in Golang.

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.