Golang is a statically-typed language with a garbage collector that makes it easy to write concurrent programs. In Golang, there are two ways to allocate memory: make
and new
. While both of these keywords can be used to allocate memory, they are used for different purposes.
new
The new
keyword in Golang is used to create a new instance of a variable, and it returns a pointer to the memory allocated. It is used for allocating memory for the value of a certain type. new
takes a type as its argument and returns a pointer to a newly allocated zero value of that type.
example of new
:
// creating a new pointer to an int variable
var x *int = new(int)
// setting the value of the newly allocated int variable
*x = 5
// output: 5
fmt.Println(*x)
In the above example, new
is used to allocate memory for an int
variable, and the pointer to this newly allocated memory is stored in the x
variable. The value of the int
variable is then set to 5
.
make
The make
keyword in Golang is used to create slices, maps, and channels, and it returns a value of the type that was created. Unlike new
, make
returns a value of the type being created, not a pointer to the type.
example of make
:
// creating a new slice with a length of 3
var s []int = make([]int, 3)
// setting the values of the slice
s[0] = 1
s[1] = 2
s[2] = 3
// output: [1 2 3]
fmt.Println(s)
In the above example, make
is used to create a new slice of int
type with a length of 3
, and the slice is stored in the s
variable. The values of the slice are then set to 1
, 2
, and 3
.
Keypoints
new
returns a pointer to the memory allocated, whilemake
returns the value of the type being created.new
only works with basic types such asint
,float
,bool
, etc.make
is used for creating slices, maps, and channels.new
allocates zeroed memory, whilemake
allocates memory and initializes it.
Conclusion
In Golang, new
and make
are two keywords that are used for allocating memory. new
is used for creating a new instance of a variable, and it returns a pointer to the memory allocated. make
is used for creating slices, maps, and channels, and it returns the value of the type being created. Knowing the differences between these two keywords is important when writing Golang code.