Range and mapping in Golang

  • date 27th August, 2022 |
  • by Prwatech |
  • 0 Comments

Range Keyword in Golang

  In Go (Golang), the range keyword is used to iterate over elements of various data structures, including arrays, slices, strings, maps, and channels. It enables efficient and idiomatic iteration without needing explicit index manipulation or iteration variables. When used with arrays, slices, or strings, range iterates over each element, returning the index and value of each iteration. This simplifies the process of iterating through collections and accessing individual elements. For maps, range iterates over key-value pairs, providing both the key and value for each iteration. This allows convenient access to map entries without manually extracting keys or values. When used with channels, range can be used to iterate over values received from the channel until the channel is closed, facilitating safe and efficient communication between goroutines. Overall, the range keyword in Go promotes clean, concise, and readable code by abstracting away low-level details of iteration. It enhances the expressiveness and simplicity of Go programs by providing a unified and consistent approach to iterating over various data structures and communication channels. Understanding and effectively using range is essential for writing efficient and idiomatic Go code. The range keyword is mainly use for loops to iterate over all the elements of a map, slice, channel, or array.
package main
import "fmt"

var Prwa = []int{1, 3, 9, 27, 81, 243, 729, 2187}

func main() {
    for i, x := range Prwa {
        fmt.Printf("3**%d=%d\n", i, x)
    }
}
Output :
PS C:\GO_Language\range> go run range.go
3**0=1
3**1=3
3**2=9
3**3=27
3**4=81
3**5=243
3**6=729
3**7=2187
  1. Initializing slices using Range.
    package main
    
    import "fmt"
    
    func main() {
        pow := make([]int, 10)
        for i:= range pow {
            pow[i] = i << uint(i)
        }
    
        for _, value:= range pow {
            fmt.Printf("%d\n", value)
        }
    }
    
    Output :
    PS C:\GO_Language\range> go run range2.go
    0
    2
    8
    24
    64
    160
    384
    896
    2048
    4608
 
  • Simple Map program
    package main
    
    import "fmt"
    
    func main() {
        var map_1 map[int]int
        if map_1 == nil {
            fmt.Println("True")
        } else {
            fmt.Println("False")
        }
    
        map_2 := map[int]string{
            90: "Red",
            91: "Yellow",
            92: "Orange",
            93: "Green",
            94: "Pink",
            95: "Blue",
            96: " ",
        }
    
        fmt.Println("Map_2", map_2)
    }
    
    Output :
    PS C:\GO_Language\range> go run range3.go
    True
    Map_2 map[90:Red 91:Yellow 92:Orange 93:Green 94:Pink 95:Blue 96: ]
    
    Range Keyword in Golang

Quick Support

image image