How to remove elements from map in Golang

WBOY
Release: 2024-02-23 10:54:04
Original
864 people have browsed it

如何在Golang中删除 map 中的元素

How to delete elements in map in Golang

In Golang, you can delete elements in map through the built-in delete function. The syntax for deleting map elements is as follows:

delete(map, key)
Copy after login

where map is the map variable that needs to be operated, and key is the key value that needs to be deleted. Next, I will use specific code examples to demonstrate how to delete elements in a map in Golang:

package main

import "fmt"

func main() {
    // 定义一个包含键值对的 map
    data := map[string]int{
        "apple":  50,
        "orange": 30,
        "banana": 20,
    }

    fmt.Println("原始 map:", data)

    // 删除键为 "orange" 的元素
    delete(data, "orange")

    fmt.Println("删除元素后的 map:", data)
}
Copy after login

In the above example, we first create a map containing key-value pairs, and then use delete The function deletes the element with the key "orange", and finally prints out the map result after the deleted element.

When the above code is run, the output result is:

原始 map: map[apple:50 banana:20 orange:30]
删除元素后的 map: map[apple:50 banana:20]
Copy after login

Through this example, we can see that the element with the key "orange" has been successfully deleted.

It should be noted that when deleting a key that does not exist in the map, the delete function will not report an error, but will be executed silently and will not affect the map. So when deleting map elements, make sure that the key you want to delete actually exists in the map.

In general, by using the delete function, we can easily delete elements in the map in Golang.

The above is the detailed content of How to remove elements from map in Golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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