how to convert map to array in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert map to array in golang, just use for loop with append() method and push one by one value in array, it will convert map to array.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows/


Today, I will show you how do I convert a map to array in golang, as above mentioned I’m going to use for and append() method.

Let’s start our Golang convert map to array example

main.go

package main

import (
	"fmt"	
)

func main() {
	m := make(map[int]string)

  m[1] = "a"
  m[2] = "b"
  m[3] = "c"
  m[4] = "d"
  
  v := make([]string, 0, len(m))
  
  for  _, value := range m {
     v = append(v, value)
  }
	fmt.Println(v)
	
}

In the above example, we have converted the map to array and printed in golang console. let’s check the output.

Output

[c d a b]

I hope it helps you, All the best 👍.

Try it Yourself

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