ADVERTISEMENT
ADVERTISEMENT

Golang program to iterate different types of data structures using the range

Here, we are going to learn how to iterate different types of data structures using the range in Golang (Go Language)?
Submitted by Nidhi, on March 25, 2021

Problem Solution:

In this program, we will create an integer array and a map. Then we will iterate elements of the array and map using the range.

Program/Source Code:

The source code to iterate different types of data structures using range is given below. The given program is compiled and executed successfully.

// Golang program to iterate different types of
// data structures using the range

package main

import "fmt"

func main() {
	intArr := []int{10, 20, 30, 40, 50}
	var CountryCode = make(map[string]int)

	CountryCode["ind"] = 101
	CountryCode["aus"] = 102
	CountryCode["eng"] = 103
	CountryCode["pak"] = 104
	CountryCode["usa"] = 105

	fmt.Printf("\nArray elements: ")
	for index, val := range intArr {
		fmt.Printf("\nIntArr[%d] : %d", index, val)
	}

	fmt.Printf("\nMap elements: ")
	for Key, Value := range CountryCode {
		fmt.Printf("\n%s : %d", Key, Value)
	}
}

Output:

Array elements:
IntArr[0] : 10
IntArr[1] : 20
IntArr[2] : 30
IntArr[3] : 40
IntArr[4] : 50
Map elements:
pak : 104
usa : 105
ind : 101
aus : 102
eng : 103

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In the main() function, we created an integer array and a map. Here, we accessed elements of the array and CountryCode map to print on the console screen.

Golang Range Programs »


ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.