Golang RangeGolang Range
0 0
Read Time:50 Second

Range can be used with an array, string, map or channels. During each iteration, range can return one or two values based on the type of collection you are iterating. Following table, provides an overview of what range returns during iteration.

Range expression1st Value2nd Value(Optional)
Array or slice a [n]Eindex i inta[i] E
String s string typeindex i intrune int
map m map[K]Vkey k Kvalue m[k] V
channel c chan Eelement e Enone
returns

Go code range

package main

import "fmt"

func main() {
	/* create a slice */
	numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}

	/* print the numbers */
	for i := range numbers {
		fmt.Println("Slice item", i, "is", numbers[i])
	}

	/* create a map*/
	countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo"}

	/* print map using keys*/
	for country := range countryCapitalMap {
		fmt.Println("Capital of", country, "is", countryCapitalMap[country])
	}

	/* print map using key-value*/
	for country, capital := range countryCapitalMap {
		fmt.Println("Capital of", country, "is", capital)
	}
}

Reference: https://www.tutorialkart.com

About Post Author

Vicky Chhetri

Responsible for website's coding, design and layout. This includes building website from concept all the way to completion from the bottom up. It might also include responsibility for the server side of web applications.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

By Vicky Chhetri

Responsible for website's coding, design and layout. This includes building website from concept all the way to completion from the bottom up. It might also include responsibility for the server side of web applications.

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *