Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Update a key in the map in Go (Golang)

Posted on June 20, 2023June 20, 2023 by admin

When trying to add a key to the map which already exists, the new value will override the old value. This is analogous to updating a key in the map.

Let’s see an example

package main
import "fmt"
func main() {
//Declare
employeeSalary := make(map[string]int)
//Adding a key value
fmt.Println("Before update")
employeeSalary["Tom"] = 2000
fmt.Println(employeeSalary)
fmt.Println("After update")
employeeSalary["Tom"] = 3000
fmt.Println(employeeSalary)
}

Output

Before update
map[Tom:2000]
After update
map[Tom:3000]

In the above program after writing the same key “Tom” with a new value of 3000 it overwrites the existing value of 2000. When we print the map again the value printed is 3000

  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP