×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Remove Element from Map in Go

Last Updated : May 27, 2025

In Go, you can remove an element from a map using the built-in delete() function. This function takes the map and the key to be removed. If the key exists, it is removed from the map; if not, the function does nothing.

Removing an Element from a Map

Use the delete() function to remove a key-value pair from a map.

Example

This example demonstrates how to remove an element from a map:

package main
import "fmt"

func main() {
    capitals := map[string]string{
        "MH": "Mumbai",
        "DL": "Delhi",
        "KA": "Bengaluru",
    }

    fmt.Println("Before deletion:", capitals)

    delete(capitals, "DL") // Remove Delhi

    fmt.Println("After deletion:", capitals)
}

When executed, this program outputs:

Before deletion: map[DL:Delhi KA:Bengaluru MH:Mumbai]
After deletion: map[KA:Bengaluru MH:Mumbai]

Deleting a Non-Existing Key

If you attempt to delete a key that doesn't exist, Go does not throw an error. The map remains unchanged.

Example

This example tries to delete a key that is not present in the map:

package main
import "fmt"

func main() {
    students := map[string]int{
        "Amit":   80,
        "Sneha":  90,
        "Rahul":  85,
    }

    delete(students, "Neha") // Key "Neha" doesn't exist

    fmt.Println("After deletion attempt:", students)
}

When executed, this program outputs:

After deletion attempt: map[Amit:80 Rahul:85 Sneha:90]

Using Delete in Conditional Logic

You can use delete() along with a check to ensure the key exists before attempting to delete it.

Example

This example checks for the existence of a key before deleting:

package main
import "fmt"

func main() {
    employees := map[string]string{
        "E101": "Arjun",
        "E102": "Priya",
        "E103": "Kiran",
    }

    if _, exists := employees["E102"]; exists {
        delete(employees, "E102")
        fmt.Println("E102 removed successfully")
    } else {
        fmt.Println("E102 not found")
    }

    fmt.Println("Updated employee list:", employees)
}

When executed, this program outputs:

E102 removed successfully
Updated employee list: map[E101:Arjun E103:Kiran]

Exercise

Select the correct answer for each question about removing map elements in Go.

  1. Which function is used to remove a key-value pair from a map?
  2. What happens if you try to delete a non-existing key?
  3. How can you check if a key exists before deleting it?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.