Allocation in Golang

In Go, allocation refers to the process of reserving memory for a variable or data structure. Memory can be allocated on the stack or the heap. Stack allocation is fast and efficient but limited in size, while heap allocation is slower but can handle much larger amounts of memory.

There are two ways to allocate memory in Go: using the built-in functions new and make.

The new function is used to allocate memory for a single value of any type. It returns a pointer to the newly allocated memory. For example, to allocate memory for an integer variable, you can use the following code:

var p *int
p = new(int)

This code declares a pointer variable p that can hold the memory address of an integer value, and then allocates memory for an integer using the new function. The memory address is assigned to the pointer variable p.

The make function is used to allocate memory for built-in data structures, such as slices, maps, and channels. It returns a value of the appropriate type, rather than a pointer to the allocated memory. For example, to allocate memory for a slice of integers, you can use the following code:

s := make([]int, 10)

This code allocates memory for a slice of 10 integers using the make function. The slice is initialized with the zero value for the element type, which is int in this case.

Practice Questions on Allocation in Golang

Here are some practice questions on allocation in Go:

Which of the following functions is used to allocate memory for a single value of any type?

A. alloc
B. make
C. new
D. malloc

Answer: C

Which of the following expressions allocates memory for a slice of 100 integers?

A. s := new([]int, 100)
B. s := make([]int, 100)
C. s := [100]int{}
D. s := []int{100}

Answer: B

Which of the following expressions allocates memory for a map with string keys and integer values?

A. m := make(map[string]int)
B. m := new(map[string]int)
C. m := [][string]int{}
D. m := []map[string]int{}

Answer: A

What is the type of the value returned by the new function?

A. Pointer to the allocated memory
B. Value of the allocated memory
C. Size of the allocated memory
D. Type of the allocated memory

Answer: A

Which of the following is an advantage of stack allocation over heap allocation?

A. Stack allocation can handle larger amounts of memory
B. Stack allocation is faster and more efficient
C. Stack allocation allows dynamic resizing of the memory
D. Stack allocation is easier to manage

Answer: B

Address operators in Golang
An example package in Golang

Get industry recognized certification – Contact us

keyboard_arrow_up