Home > Backend Development > Golang > How do I Delete Keys from a Go Map?

How do I Delete Keys from a Go Map?

DDD
Release: 2024-12-06 10:05:12
Original
349 people have browsed it

How do I Delete Keys from a Go Map?

Deletion in Go Maps

In Go, maps are a versatile data structure used to store key-value pairs. Deleting keys from a map can be crucial for memory management or altering the stored data. This question addresses how to remove a key from a map in Go.

Pre-Go v1 Deletion

Before version 1 of Go, there was no dedicated syntax for deleting map entries. Users had to resort to assigning nil to the corresponding map value:

sessions[key] = nil, false
Copy after login

However, this approach was ineffective as it only nullified the value associated with the key, leaving the key itself in the map.

Go v1: Introduction of delete function

In Go version 1, the delete function was introduced as the preferred way to remove keys from maps:

package main

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

The delete function takes two arguments: the map to modify and the key to delete. It effectively removes the specified key and its associated value from the map.

Usage of delete function

To remove a key called "moo" from the sessions map:

delete(sessions, "moo")
Copy after login

After calling delete, the sessions map will no longer contain the "moo" key or its corresponding value.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template