Go provides a built-in function delete() to delete elements in containers. Let’s briefly introduce how to use the delete() function to delete elements in maps.
Use the delete() function to delete key-value pairs from map
Use the delete() built-in function to delete a set of key-value pairs from the map. The format of the delete() function is as follows:
delete(map, key)
where map is the map instance to be deleted, and the key is the key of the key-value pair in the map to be deleted.
Deleting a set of key-value pairs from a map can be done by following the following code:
scene := make(map[string]int) // Prepare map datascene["route"] = 66 scene["brazil"] = 4 scene["china"] = 960 delete(scene, "brazil") for k, v := range scene { (k, v) }
The code output is as follows:
route 66
china 960
In this example, using the delete() function deletes the brake from the scene map.
Clear all elements in the map
Interestingly, the Go language does not provide any functions or methods for clearing all elements for maps. The only way to clear maps is to make a new map again, and there is no need to worry about the efficiency of garbage collection. Parallel garbage collection in Go language is much more efficient than writing a clearing function.
This is the article about deleting and clearing Go map elements. For more relevant content on deleting and clearing Go map elements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!