How to get the last element of a map in golang?
October 31, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To get the last 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 print the last iteration
Today, I’m going to get the last element of a map in golang, here we will two ways to get the last element of the map.
Here, we will see an example
- Get the last element without for loop
- Get the last element with for loop
Let’s start
Get the last element without for loop
Here, we will access elements by their key, you can follow this example if you know what’s your last element key.
package main
import (
"fmt"
)
func main() {
mymap := make(map[string]string)
mymap["first"] = "aguidehub"
mymap["second"] = "infinitbility"
mymap["third"] = "sortoutcode"
fmt.Println("last Element without loop", mymap["third"])
}
In the above program, we are trying to access value from their key, let’s see the output.
Output:
last Element without loop sortoutcode
Get last element with for loop
This case helps us when we don’t know the last element key, their data type, and another thing, in this case, we use a loop and get their last key to access their last element.
package main
import (
"fmt"
)
func main() {
mymap := make(map[string]string)
mymap["first"] = "aguidehub"
mymap["second"] = "infinitbility"
mymap["third"] = "sortoutcode"
index := 0
for k := range mymap {
index++
if(index == len(mymap)){
fmt.Println("last Element key", k)
fmt.Println("last Element vlaue", mymap[k])
}
}
}
In the above program, we are used for loop and break statements to get the last element dynamically, let’s check the output.
Output:
last Element key third
last Element vlaue sortoutcode
All the best 👍