×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go - new() and make() Functions

By IncludeHelp Last updated : October 05, 2024

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.

Syntx

    result = new(int)

is equivalent to

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

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

Syntax

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.

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.