new() and make() functions with examples in Golang

Golang new() and make() functions: In this tutorial, we are going to learn about the two built-in functions new() and make() to allocate memory dynamically with their descriptions, syntaxes, examples.
Submitted by Anshuman Singh, on June 14, 2019 [Last updated : March 05, 2023]

In Golang, to allocate memory, we have two built-in functions new() and make().

Golang new() function

  • Memory returned by new() is zeroed.
  • new() only returns pointers to initialized memory.
  • new() works for all the data types (except channel, map), and dynamically allocates space for a variable of that type and initialized it to zero value of that type and return a pointer to it.

Example

    result = new(int)

is equivalent to

    var temp int   // declare an int type variable
    var result *int //  declare a pointer to int
    result = &temp 

Golang code for demonstrate the example of new() function

There are three different ways to create a pointer that points to a zeroed structure value, each of which is equivalent:

package main

import "fmt"

type Sum struct {
	x_val int
	y_val int
}

func main() {
	// Allocate enough memory to store a Sum structure value
	// and return a pointer to the value's address
	var sum Sum
	p := &sum
	fmt.Println(p)

	// Use a composite literal to perform 
	//allocation and return a pointer
	// to the value's address
	p = &Sum{}
	fmt.Println(p)

	// Use the new function to perform allocation, 
	//which will return a pointer to the value's address.
	p = new(Sum)
	fmt.Println(p)
}

Output

&{0 0}
&{0 0}
&{0 0}

Golang make() function

make() only makes slices, maps, and channels. make returns value of type T(data type) not *T

Example

make([]int, 10, 20) – Here, make creates the slice, and initialize its content depending on the default data type value. here int is used, so the default value is 0.

new([20]int)[0:10] – Here, It will also create slice but returns pointers to initialized memory.

Golang code for demonstrate the example of make() function

There are two different ways to initialize a map which maps string keys to bool values are given below.

package main

import "fmt"

func main() {
	// Using make() to initialize a map.
	m := make(map[string]bool, 0)
	fmt.Println(m)

	// Using a composite literal to initialize a map.
	m = map[string]bool{}
	fmt.Println(m)
}

Output

map[]
map[]

Reference: allocation_new



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.