Go Example: Range

1. Introduction

The range keyword in Go is a versatile and powerful tool for iterating over elements of various data structures. It can be used with slices, maps, channels, and other types. This post will illustrate how to use range to iterate over slices and maps in Go.

Definition

range in Go provides a way to iterate over elements in a variety of data structures. When used with slices, it returns two values: the index and the value at that index. When used with maps, it returns key-value pairs.

2. Program Steps

1. Use range with a slice.

2. Use range with a map.

3. Iterate over a slice to sum the values.

4. Iterate over a map to print the key-value pairs.

5. Use range to iterate over a string.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Use range with a slice
	nums := []int{2, 3, 4}
	sum := 0
	for _, num := range nums {
		sum += num
	}
	fmt.Println("sum:", sum)

	// Step 2: Use range with a map
	kvs := map[string]string{"a": "apple", "b": "banana"}
	for k, v := range kvs {
		fmt.Printf("%s -> %s\n", k, v)
	}

	// Step 3: Use range to iterate over a string
	for i, c := range "go" {
		fmt.Println(i, c)
	}
}

Output:

sum: 9
a -> apple
b -> banana
0 103
1 111

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for printing output to the console.

3. nums is a slice of integers, iterated over using range. The underscore (_) is used to ignore the index.

4. In the loop, sum accumulates the values of the elements in nums.

5. kvs is a map from strings to strings. A range loop iterates over it, printing each key-value pair.

6. Finally, range is used to iterate over the string "go". The loop prints the index of each character and the Unicode code point of the character, not the character itself.

7. The output includes the sum of the numbers in the slice, the contents of the map, and the index and Unicode code point for each character in the string "go".


Comments