0% found this document useful (0 votes)
12 views

Go by Example - Range Over Built-In Types

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Go by Example - Range Over Built-In Types

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Go by Example: Range over Built-in Types https://gobyexample.

com/range-over-built-in-types

Go by Example: Range over Built-in Types


range iterates over elements in a variety of built-in
data structures. Let’s see how to use range with
some of the data structures we’ve already learned.

package main

import "fmt"

func main() {

Here we use range to sum the numbers in a slice. nums := []int{2, 3, 4}


Arrays work like this too. sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)

range on arrays and slices provides both the index for i, num := range nums {
and value for each entry. Above we didn’t need the if num == 3 {
index, so we ignored it with the blank identifier _. fmt.Println("index:", i)
}
Sometimes we actually want the indexes though.
}

range on map iterates over key/value pairs. kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}

range can also iterate over just the keys of a map. for k := range kvs {
fmt.Println("key:", k)
}

range on strings iterates over Unicode code points. for i, c := range "go" {
The first value is the starting byte index of the fmt.Println(i, c)
rune and the second the rune itself. See Strings }
}
and Runes for more details.

$ go run range-over-built-in-types.go
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Next example: Pointers.

by Mark McGranaghan and Eli Bendersky | source | license

1 of 1 11/26/24, 23:34

You might also like