Home >Backend Development >Golang >When and Why Should You Use `new` with Structs in Go?
Understanding the Purpose of new in Go
Contrary to primitive language constructs, using new with structs offers some utility. While new(MyStruct) and &MyStruct{} achieve similar outcomes, their choice depends on the clarity and expressiveness of the code.
new plays a crucial role in initializing non-primitive data types such as structs. Go's lack of constructor support can be addressed by wrapping new into custom functions (e.g., NewMyStruct()). This approach enables flexible initialization, including the manipulation of private fields and the provision of custom constructors to prevent uncontrolled access to the struct's internals. It also simplifies structural adjustments, avoiding disruptions to existing users when modifying the struct's layout.
Remember, slices and maps cannot be initialized using new. Instead, the make command is required, as in make([]float, 100).
The above is the detailed content of When and Why Should You Use `new` with Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!