menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

make vs ne...
source image

Dev

2w

read

261

img
dot

Image Credit: Dev

make vs new in Go: Differences and Best Practices

  • In Go, make and new are both keywords for memory allocation, but they have distinct roles and usage scenarios.
  • new allocates memory for a type and returns a pointer to that memory, initializing it to the zero value of the type.
  • make initializes slices, maps, and channels, returning the initialized object itself without a pointer.
  • Tips for using new: suitable for allocating memory for struct types and initializing them with zero values.
  • Tips for using make: useful for initializing slices with specified capacity, maps with initial capacity, and buffered channels.
  • Performance considerations: make incurs additional overhead due to type initialization, while new is more straightforward.
  • Common misuse: Incorrectly using new for slices, maps, or channels can lead to runtime errors; make should be used for initialization.
  • Choosing the appropriate method: Use new for simple allocations and make for initializing slices, maps, and channels with advanced requirements.
  • Understanding the differences and choosing the right method can lead to more efficient and maintainable Go code.
  • Leapcell offers a serverless platform for hosting Go projects, providing cost efficiency, scalability, and a streamlined developer experience.

Read Full Article

like

15 Likes

For uninterrupted reading, download the app