Golang built-in functions the difference between the initialization of new () and struct{}

Source: Internet
Author: User

Golang built-in functions the difference between the initialization of new () and struct{}

Happinessaflower 2015-06-17 20:03:41 13,036 reads • Estimated reading time 1 minutes • Start browsing about 1 minutes ago

This is an article created in 2015-06-17 20:03:41, where the information may have evolved or changed.

New ()

This is a built-in function for allocating memory, the first parameter of which is a type, not a value, and its return value is a pointer to a 0 value of the newly assigned T type.

The code in Golang is defined as follows:

Funcnew (ttype) *type

strut{}

When initializing strut directly using struct{}, the value returned is a struct type, not a pointer.

The comparison code is as follows:

typestudentstruct{Idintnamestring}funcmain () {vars_1 *student =new (Student) s_1.id = 100s_1.name = "Cat" Vars_2 Studen t = student{id:1,name: "Tom"} FMT. Println (S_1,s_2)}

Output Result:

&{100 Cat} {1 Tom}

From the declaration of the above Code and the result of printing, we can see that the type of s_1 is a pointer, s_2 is a student type

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.