Basic map usage in Go language

PHPz
Release: 2024-03-24 13:09:04
Original
819 people have browsed it

Basic map usage in Go language

Go language is an open source programming language that is efficient and concise. One of its data structures is map. In the Go language, map is a "key-value pair" data structure that can be used to store a series of unordered key-value pairs. This article will introduce in detail the basic use of map in Go language and provide specific code examples.

1. Create a map

In the Go language, you can use the built-in make function to create an empty map. The syntax is as follows:

m := make(map[string]int) // 创建一个键为字符串,值为整数的map
Copy after login

2. Add key-value pairs

To add key-value pairs to the map, you can use map[key] = value. The example is as follows:

m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
Copy after login

3. Get the value

Get it by key For the corresponding value, you can use map[key]. The example is as follows:

fmt.Println(m["apple"]) // 输出:5
Copy after login

4. Determine whether the key exists

When getting the value, sometimes you need to determine whether the key exists. You can Use the "comma ok" syntax, the example is as follows:

value, ok := m["orange"]
if ok {
    fmt.Println("orange的值为:", value)
} else {
    fmt.Println("orange不存在")
}
Copy after login

5. Delete the key-value pair

To delete the key-value pair in the map, you can use the delete function, the example is as follows:

delete(m, "banana")
Copy after login

6. Map traversal

Use the for loop and range keyword to traverse the key-value pairs in the map. The example is as follows:

for key, value := range m {
    fmt.Println(key, ":", value)
}
Copy after login

7. The length of the map

You can use the len function to get the number of key-value pairs in the map. The example is as follows:

fmt.Println("map的长度为:", len(m))
Copy after login

Through the above code examples, we can clearly understand how to use the map data structure in the Go language. The flexibility and efficiency of map make it one of the commonly used data structures in the Go language. Hope this article is helpful to beginners.

The above is the detailed content of Basic map usage in Go language. 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