How to get a slice of keys from a map in Golang

Last updated on Sep 17, 2022 by Suraj Sharma



In this tutorial, you will learn how you can get a slice of keys from a map in Golang


To get a slice of keys from a map we iterate through the map using range statement to extract keys and values from the map


  package main

  import "fmt"

  func main () {
    keys := make([]interface{}, 0)
    demoMap := make(map[string]string)
    demoMap["Mon"] = "Monday"
    demoMap["Tue"] = "Tuesday"
    demoMap["Wed"] = "Wednesday"

    //get a slice of keys from the demoMap
    for k, _:= range demoMap {
      keys = append(keys, k)
    }
    fmt.Printf("keys are %v", keys) //[Mon Tue Wed]
  }


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.