How to remove a key from a map in Golang

Last updated on Sep 12, 2022 by Suraj Sharma



In this tutorial, you will learn how to remove an existing key from a map in Golang


We use a built-in delete function to remove the key from the map.

It is always important to check if the key exists in the map to prevent panic.


Example


  package main

  func main () {
    simpleMap := make(map[int]string, 0)
    simpleMap[1] = "One"
    simpleMap[2] = "Two"

    // delete a key from the map
    // check if the key exists in the map
    // to prevent the program to raise a panic
    if _, ok := simpleMap[2]; ok {
      delete(simpleMap, 2)
    }
  }


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.