In golang, the method of deleting a map is very simple. Use the built-in function delete
to complete the deletion operation.
In golang, map is an unordered data structure that can store and access data using key-value pairs. To delete elements in a map, you can use the delete
function. The format of this function is as follows:
delete(map, key)
Among them, map
represents the map object of the element to be deleted, and key
represents the key value of the element that needs to be deleted. When the specified key value exists in the map, the delete
function will delete the corresponding key-value pair from the map. If the specified key value does not exist, the function does nothing and returns directly.
The following is a simple example that demonstrates how to use the delete
function to delete elements in the map:
package main import "fmt" func main() { // 定义一个map myMap := map[string]string{ "key1": "value1", "key2": "value2", "key3": "value3", } // 删除key2对应的value delete(myMap, "key2") // 遍历map for key, value := range myMap { fmt.Printf("key: %s, value: %s ", key, value) } }
In the above example, we created a map containing 3 elements map, and use the delete
function to delete the key2
element, and finally traverse the map and print out the key-value pairs.
In general, it is very simple to use the delete
function to delete elements in the map. You only need to specify the key value to be deleted to complete the operation. When writing code, we should pay attention to check whether the specified key value exists to avoid errors.
The above is the detailed content of How to delete map in golang. For more information, please follow other related articles on the PHP Chinese website!