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

Try it Yourself

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, First Element with loop, golang

Try it Yourself

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.

get, Random Element with loop, golang

Try it Yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts