How to find the capacity of the pointers pointing at a map in Golang?


A pointer is a variable which holds the address of another variable and can be used to point to the content of another variable. A pointer does not have its capacity just like slices, it can be used to point to the map whose length of elements can be calculated.In this article, we will write a Go language program to find the capacity of a pointer pointing to a map.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Algorithm

  • Step 1 − This program imports the main and fmt as necessary packages

  • Step 2 − Create a main function

  • Step 3 − In the main, create a map using make as a built-in function where the keys are of type string and values are of type int

  • Step 4 − In this step, assign values to the keys in the map

  • Step 5 − Then, using the ampersand symbol, create a variable which points to the map

  • Step 6 − In this step, use len method to count the key-value pairs in the map with the help of pointer variable

  • Step 7 − Store the output in the count variable

  • Step 8 − Print the count variable on the console using Println from the fmt package where ln means new line

Example

In this example, we will write a Go language program to find the capacity of a pointer pointing to a map using ampersand which points to the variable that will be dereferenced to calculate the length of items in the map.

package main
import "fmt"

func main() {
	Map := make(map[string]int)
	Map["a"] = 10
	Map["b"] = 20
	Map["c"] = 30
	Map["d"] = 40
	Map["e"] = 50

	point := &Map

	count := len(*point)
	fmt.Println("Number of elements:", count)
}

Output

Number of elements: 5

Conclusion

In this article we have explored a way to find the capacity of a pointer pointing to a map using an ampersand symbol by which the variable is used to calculate the length of the map.

Updated on: 06-Jul-2023

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements