How to add a key to a map in Golang

Last updated on Oct 22, 2022 by Suraj Sharma



In this tutorial, you will learn how you can add a key to a map in Golang so that it does not override the existing key's value


The easiest way to add a new key to a map in Golang is to simply do


m := make(map[string]int)
m["apple"] = 1

However, it might override the existing key's value if the key you want to add is already present in the map


m := make(map[string]int)
m["apple"] = 1
m["apple"] = 2 //overrides the previous value of "apple"

Therefore, to be on the safer side, you can check if the key exists in a map before adding the key to the map.


package main

import "fmt"

func main () {
  m := make(map[string]int)
  m["apple"] = 1
  m["mango"] = 2
  
  if val, isKeyExists := m["blueberry"]; isKeyExists {
    fmt.Printf("key exists: value [%d]\n", val)
  } else {
    m["blueberry"] = 3
  }
  fmt.Printf("%v", m)
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.