How to get the first element of a map in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To get the first element of a map, we have the following two ways

  1. If you know the key, then you can directly access the element using a key like myMap[key].
  2. 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

  1. Get the first element without for loop
  2. Get the first element with for 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 without loop, golang

Try it yourself

Get first element with for loop

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"
)

func main() {
    mymap := make(map[int]string)
    mymap[0] = "aguidehub"
    mymap[1] = "infinitbility"
    mymap[2] = "sortoutcode"

    for k := range mymap {
        fmt.Println("First Element with loop", 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, First Element with loop, golang

Try it yourself

All the best 👍

Follow me on Twitter