Home  >  Article  >  Backend Development  >  ## What\'s the Difference: `new(MyStruct)` vs. `&MyStruct{}` in Go?

## What\'s the Difference: `new(MyStruct)` vs. `&MyStruct{}` in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 06:54:29685browse

## What's the Difference: `new(MyStruct)` vs. `&MyStruct{}` in Go?

Understanding the Role of new in Go

Contrary to its appearance in primitive language constructs, new finds its purpose in creating pointers. While you cannot directly specify values for primitives with new, it becomes a useful tool for allocating memory for structured data types like structs. In such scenarios, new returns a pointer to an uninitialized object, allowing you to work with its properties later on.

Differentiating new and &

While both new(MyStruct) and &MyStruct{} yield a pointer to a new struct instance, their usage depends on the code's intent. Sometimes, the conciseness of &MyStruct{} is preferred, while new(MyStruct) explicitly showcases the intent to allocate memory on the heap.

Other Considerations for new

Beyond primitive types and structs, new is not applicable to slices and maps. Instead, make([]float, 100) should be used for slices.

Practical Applications of new

Since Go lacks built-in constructors, developers often wrap new calls within custom functions to initialize and customize objects. This approach simplifies initialization processes, allows for hiding private fields, and eases structural evolution. Furthermore, it provides flexibility by decoupling the object's creation from its usage, enabling developers to make changes to the struct's structure without affecting existing code.

The above is the detailed content of ## What\'s the Difference: `new(MyStruct)` vs. `&MyStruct{}` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn