How to get all the values from map in golang?
May 02, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To get all values from map, you can use range
to get value from map and store in an new array where you can store all values and use wherever you want.
Today, we are going to do how to get all the values from the map in golang, here we will write simple logic to extract all values from the map using loops.
Well, First we will create a map variable with sample data, after that we will create the values
variable where we will store our values.
After the creation of the variable, we will write a range where we can get a value by key to map, and we will store those values in our values
variable one by one.
Let’s start our code part.
package main
import "fmt"
func main() {
mymap := map[int]string{
1: "Hello",
2: "World",
3: "Of Infinitbility",
}
values := make([]string, len(mymap))
i := 0
for k := range mymap {
values[i] = mymap[k]
i++
}
fmt.Println(values)
}
When run above program you will get a golang map values basically range is loop which can help you get value by key from map in golang.
Using fmt.Println
method golang print all values in map.
Let’s see actual output of the code.
Here, we are provided code onecompiler links for the above program for get all values from map. Then you can use it whenever you want and do the changes as per your requirements.
Happy Coding,
I hope the above example with help you to do your task.