Home >Backend Development >Golang >Basic usage and modification methods of Golang Map

Basic usage and modification methods of Golang Map

王林
王林Original
2024-03-03 08:33:03575browse

Golang Map的基本用法及修改方法

Golang is a programming language known for its performance and concurrency advantages. One of its built-in data structures is Map. Map is an unordered collection of key-value pairs, similar to a dictionary or hash table in other languages. In Golang, Map is created using the make() function. Its basic usage and modification methods are as follows.

Basic usage

First, let’s take a look at how to declare and initialize a Map:

package main

import "fmt"

func main() {
    // 创建一个空的Map
    var m map[string]int
    m = make(map[string]int)
    
    // 添加键值对
    m["apple"] = 10
    m["banana"] = 20

    // 访问键值对
    fmt.Println("apple:", m["apple"])
    fmt.Println("banana:", m["banana"])

    // 删除键值对
    delete(m, "apple")

    // 判断键是否存在
    value, ok := m["apple"]
    if ok {
        fmt.Println("apple存在,值为:", value)
    } else {
        fmt.Println("apple不存在")
    }

    // 遍历Map
    for key, value := range m {
        fmt.Println(key, ":", value)
    }
}

Modification methods

In addition to basic addition, access, and deletion In addition to key-value pairs, we can also modify the values ​​in the Map through direct assignment:

package main

import "fmt"

func main() {
    m := make(map[string]int)

    m["apple"] = 10
    fmt.Println("apple的值为:", m["apple"])

    // 直接赋值修改
    m["apple"] = 15
    fmt.Println("修改后的apple的值为:", m["apple"])
}

In addition, we can also determine whether the key exists and then modify the key-value pair to ensure that it does not An error occurred because of accessing a non-existent key:

package main

import "fmt"

func main() {
    m := make(map[string]int)

    m["apple"] = 10

    if value, ok := m["apple"]; ok {
        m["apple"] = value + 5
        fmt.Println("修改后的apple的值为:", m["apple"])
    } else {
        fmt.Println("apple不存在")
    }
}

In general, Map in Golang is a very convenient and practical data structure, suitable for storing key-value pairs, and its basic usage and modification methods are also All very simple and intuitive. Through the introduction of this article, I believe that readers have a deeper understanding of the basic usage and modification methods of Map in Golang.

The above is the detailed content of Basic usage and modification methods of Golang 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