New and make for Go language

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

The main differences between the new and make of Golang are as follows:

1. Make can only be used to assign and initialize data of type Slice,map,chan; New can assign any type of data

2, the new assignment returns a pointer, that is, the type *t;make return reference, that is, T;

3. The new allocated space is zeroed, and when make is allocated, it is initialized. Effective go for an example, see: Http://golang.org/doc/effective_go.html#allocation_make

For the assignment and initialization of structs, you can do this in addition to using new: T {}, for example

Func testalloc (t *testing. T) {type T struct {n  stringi  intf  float64fd *os. Fileb  []bytes  bool}var T1 *tt1 = new (T) fmt. Println (t1) t2: = T{}fmt. Println (t2) T3: = t{"Hello", 1, 3.1415926, nil, make ([]byte, 2), true}fmt. Println (T3)}

It is important to note that if you initialize a variable using t{}:
1, unlike the C language, the local variable assigned by t{} can be returned, and the space will not be released after returning, for example

Import "FMT" type T struct {    I, J Int}func A (i, J int) T {    I: = t {i, J}    return I}func b {    T = a (1, 2) 
  
   fmt. Println (t)}
  

2, a grammatical problem
When initializing with t{}, the symbol} cannot have a single exclusive line, otherwise it will error, as follows:

Missing ', ' before newline in composite literal

Or

Syntax error:need trailing comma before newline in composite literalnon-declaration statement outside function Bodysyntax error:unexpected}

I've been looking for this problem for a long time before I solve it.

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.