Golang : When to use make or new?
Tags : golang make new slices maps buffers
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 :
Tags : golang make new slices maps buffers
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
+8.1k Golang : Get time.Duration in year, month, week or day
+11.5k Golang : Change a file last modified date and time
+6.4k Golang : [json: cannot unmarshal object into Go value of type]
+2.6k Golang : Clone with pointer and modify value
+6.9k Golang : Use TLS version 1.2 and enforce server security configuration over client
+4.8k Golang : How To Use Panic and Recover
+1.7k How to check with curl if my website or the asset is gzipped ?
+3.5k Gogland : Where to put source code files in package directory for rookie
+1.9k Golang : How to check variable or object type during runtime?
+4.5k Golang : Generate random integer or float number
+2.1k Golang : Pat multiplexer routing example
+2.4k Unix/Linux : Use netstat to find out IP addresses served by your website server