"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What\'s the Difference Between the \"new()\" Function and the \"&\" Memory Address Operator in Go?

What\'s the Difference Between the \"new()\" Function and the \"&\" Memory Address Operator in Go?

Published on 2024-11-08
Browse:403

What\'s the Difference Between the \

The Differences Between new() and "&" Operator

In Go, the new() function and the "&" memory address operator are both used to allocate memory. However, there are some subtle differences between their usage.

Functionality Comparison

Both new() and & operator return a pointer to a newly allocated memory address. However, they differ in their syntax:

  • v := &Vector{} uses the "&" operator to obtain the address of an empty Vector struct.
  • v := new(Vector) uses the new() function to create a pointer to a new Vector struct.

Type Analysis

As demonstrated by the provided code example, reflection analysis shows that both &Vector{} and new(Vector) return pointers of the same type, as both are pointers to instances of the Vector struct.

Historical Confusion

The Go mailing list has previously discussed concerns about having both new() and & for memory allocation, as it can lead to confusion.

Special Case

It's worth noting that new() is the only method to obtain a pointer to an unnamed basic type, such as an integer. This can be seen in the following example:

p := new(int) // valid
p := &int{0} // invalid

Preference and Usage

Ultimately, the choice between using new() and & for memory allocation is largely a matter of personal preference. Both methods have the same functionality and produce the same results. However, it's important to be aware of the subtle differences between the two operators and to use them appropriately based on specific requirements.

Release Statement This article is reprinted at: 1729661717 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3