Golang : When to use make or new?
Problem :
When to use make
or new
in Golang ? It can be confusing for newbie to Golang.
Solution :
In the simplest example that I can think of....
- Imagine
new
as someone that creates an empty box and points the direction(pointer or address) of the empty box to you. - and
make
as someone that creates a box filled with values that defined by you and pass the non-empty box to you....not pointer or address.
Use new
when you want to :
- create a new file and save data to the the NEW file
- create or allocate a new buffer for you to store some data, manipulate the buffer and then flush the data to somewhere else such as a pipe.
Use make
when you want to :
- use maps, slices and channels and want to manipulate the data in them directly instead of a pointer or address.
- pre-fill the maps, slices and channels with initial values.
- specify the size or increase/decrease the size of maps or slices during runtime.
Remember...the rule of the thumb is
new
= empty box with pointermake
= filled box without pointer
Hope this simple tutorial can be useful to you. Happy coding!
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.3k Golang : Sort and reverse sort a slice of bytes
+25.4k Golang : missing Mercurial command
+11.3k CodeIgniter : Import Linkedin data
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+5.6k Golang : Launching your executable inside a console under Linux
+10k Golang : Convert file unix timestamp to UTC time example
+12.8k Golang : List objects in AWS S3 bucket
+10.3k Android Studio : Checkbox for user to select options example
+15k Golang : Delete certain files in a directory
+8.8k Golang : How to use Gorilla webtoolkit context package properly
+9.8k Golang : Test a slice of integers for odd and even numbers
+35.7k Golang : Converting a negative number to positive number