Make and New in Golang

Source: Internet
Author: User

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

New:new (t) allocates a 0 value to the memory space of the type T, and returns its address, which is the value of a *t type. itself is a pointer. Can be used to initialize any type

Make: Returns a T type with an initial value (not 0), instead of *t, which can only be used to initialize: Slice,map and channel three types.

Contrast:

    1. Scope of application: Make can only create built-in types (slice map channel), and new is memory-allocated for all types
    2. Return value: New Returns a pointer, make returns a reference
    3. Padding value: New fills 0 values, make fills non 0 values

Code:

Package Mainimport ("FMT"    "reflect") Type Booksstruct{Title, Content, Authorstring}func Main () {a:=New([]int) fmt. Println (a)//the output &[],a itself is an addressB: = make ([]int,1) fmt. Println (b)//The output [0],b itself is a slice object whose content defaults to 0Book1:=New(Books) Book1. Title="This is Book1 title"Book1. Content="This is Book1 content"Book1. Author="This is Book1 author"Book2:= books{"This is book2 title","This is book2 content","This is book2 author"} fmt. Println ("Book1:", Book1,", Type:", reflect. TypeOf (Book1))
//Book1: &{this is Book1 title This is Book1 content this is Book1 author}, Type: *main. BooksFmt. Println ("Book2:", Book2,", Type:", reflect. TypeOf (BOOK2))
//Book2: {This was Book2 title this is BOOK2 content of this is Book2 author}, Type:main. Books}

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.