How to get the first element of a map in golang?
June 18, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To get the first element of a map, we have the following two ways
- If you know the key, then you can directly access the element using a key like
myMap[key]
. - use the
for...range
loop and break after the first iteration.
Today, I’m going to get the first element of a map in golang, here we will two ways to get the first element of the map.
Here, we will see an example
- Get the first element without range loop
- Get the first element with range loop
- Get the random element with range loop
Let’s start
Get the first element without for loop
Here, we will access elements by their key, you can follow this example if you know what’s your first element key.
package main
import (
"fmt"
)
func main() {
mymap := make(map[int]string)
mymap[0] = "aguidehub"
mymap[1] = "infinitbility"
mymap[2] = "sortoutcode"
fmt.Println("First Element without loop", mymap[0])
}
In the above program, we are trying to access value from their key, let’s see the output.
Get first element with range and sort
This case helps us when we don’t know the first element key, their data type, and another thing, in this case, we use a loop and get their first key to access their first element.
package main
import (
"fmt"
"sort"
)
func main() {
mymap := make(map[int]string)
mymap[0] = "aguidehub"
mymap[1] = "infinitbility"
mymap[2] = "sortoutcode"
keys := make([]int, 0)
for k, _ := range mymap {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println(k, mymap[k])
break
}
}
In the above program, we are used for loop and break statements to get the first element dynamically, let’s check the output.
Get random element with range
Here, I will take random element from map using range loop so let’s see the code.
package main
import (
"fmt"
)
func main() {
mymap := make(map[int]string)
mymap[0] = "aguidehub"
mymap[1] = "infinitbility"
mymap[2] = "sortoutcode"
for k := range mymap {
fmt.Println("Random Element with loop", mymap[k])
break
}
}
In the above program, we are used range loop and break statements to get the random element dynamically, let’s check the output.
All the best 👍