Home >Backend Development >Golang >How Do I Delete a Key from a Go Map?

How Do I Delete a Key from a Go Map?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 18:45:15176browse

How Do I Delete a Key from a Go Map?

Removing a Key from a Go Map

Maps are data structures that associate keys with values. Deleting a key from a map is often necessary to manage data and maintain its integrity.

One method to delete a key from a map in Go is using the delete function. The delete function takes two arguments: a map and a key, and removes the specified key from the map. For example:

package main

func main() {
    var sessions = map[string]chan int{}
    delete(sessions, "moo")
}

This code will delete the key "moo" from the sessions map.

Historical Syntax

Prior to Go version 1, deleting a key from a map involved setting the value associated with the key to nil. This syntax is no longer supported in Go 1 and onwards.

Example Usage

The following code snippet illustrates how to use the delete function:

var sessions = make(map[string][]string)
sessions["user1"] = []string{"John", "Doe"}
sessions["user2"] = []string{"Jane", "Doe"}

delete(sessions, "user1")

After executing this code, the user1 key will be removed from the sessions map, leaving only the user2 key.

The above is the detailed content of How Do I Delete a Key from a Go Map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn