Home Backend Development Golang Understand and apply examples of GolangMap

Understand and apply examples of GolangMap

Jan 16, 2024 am 10:12 AM
golang map Application examples

Understand and apply examples of GolangMap

GolangMap Introduction and Application Examples

Golang is a programming language developed by Google and is widely used in web development, cloud computing, embedded systems and other fields. Among them, Map is a data structure in Golang, used to store key-value pairs. This article will introduce the basic usage of GolangMap and its practical application examples.

Basic usage of GolangMap

Golang's Map is an unordered collection of key-value pairs, where the keys and values ​​can be of any type. The declaration and initialization method of Map is as follows:

//声明一个Map
var map1 map[string]int

//初始化Map
map1 = make(map[string]int)

//或者声明并初始化Map
map2 := make(map[string]int)
Copy after login

Among them, the first example declares an uninitialized Map, and the second example declares and initializes a Map, which can be used as needed. To add a key-value pair in a Map, you can use the following method:

//添加键值对
map1["one"] = 1
map1["two"] = 2
map1["three"] = 3
Copy after login

To access the value corresponding to a key in the Map, you can use the following method:

//访问键对应的值
value := map1["one"]
Copy after login

If you access a non-existent key, it will Returns the zero value of this type. If you need to determine whether the key exists, you can use the following method:

//判断键是否存在
value, ok := map1["four"]
if ok {
    fmt.Println("the value of four is", value)
} else {
    fmt.Println("four does not exist in the map")
}
Copy after login

The second return value is of bool type, indicating whether the key exists.

Application examples of GolangMap

In practical applications, GolangMap can be used to solve many problems. Several examples will be introduced below.

  1. Count the number of times a word appears

Suppose we now need to count the number of times each word appears in an article. We can use Map to achieve this:

package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "A happy family is but an earlier heaven."
    words := strings.Fields(text)

    wordCount := make(map[string]int)
    for _, word := range words {
        wordCount[word]++
    }

    for word, count := range wordCount {
        fmt.Printf("%s:%d ", word, count)
    }
}
Copy after login

Among them, strings.Fields(text) can split the text into a word list, then traverse the word list, count the number of occurrences of each word, and finally output each word and its number of occurrences.

  1. Implementing Cache

Suppose we need to implement a cache system that can store some objects in memory to improve program performance. We can use Map to achieve:

package main

import (
    "fmt"
    "sync"
    "time"
)

type Cache struct {
    sync.RWMutex
    data map[string]interface{}
}

func NewCache() *Cache {
    return &Cache{data: make(map[string]interface{})}
}

func (c *Cache) Get(key string) (interface{}, bool) {
    c.RLock()
    defer c.RUnlock()
    val, ok := c.data[key]
    return val, ok
}

func (c *Cache) Set(key string, value interface{}) {
    c.Lock()
    defer c.Unlock()
    c.data[key] = value
}

func main() {
    cache := NewCache()

    cache.Set("key1", "value1")
    cache.Set("key2", "value2")

    fmt.Println(cache.Get("key1"))
    fmt.Println(cache.Get("key2"))

    time.Sleep(time.Second * 2)

    fmt.Println(cache.Get("key1"))

    cache.Set("key2", "new value2")

    fmt.Println(cache.Get("key2"))
}
Copy after login

Among them, the NewCache() function is used to initialize an empty Cache object, the Get() function is used to obtain the value corresponding to a certain key, and the Set() function is used to add Or modify the value corresponding to a key. In the main() function, we first add two key-value pairs, then output their values, and then wait for 2 seconds and output the value of one of the keys again. You can see that the cache has not expired, and then modified the corresponding key value, and finally output the value of the key.

  1. Implementing message queue

Suppose we need to implement a message queue, which can store some messages in memory to achieve asynchronous processing. We can use Map to achieve:

package main

import (
    "fmt"
    "sync"
)

type MessageQueue struct {
    sync.Mutex
    data map[int]string
    index int
}

func NewMessageQueue() *MessageQueue {
    return &MessageQueue{data: make(map[int]string)}
}

func (mq *MessageQueue) Enqueue(msg string) {
    mq.Lock()
    defer mq.Unlock()

   mq.index++
    mq.data[mq.index] = msg
}

func (mq *MessageQueue) Dequeue() string {
    mq.Lock()
    defer mq.Unlock()

    msg, ok := mq.data[1]
    if !ok {
        return ""
    }

    delete(mq.data, 1)
    for i := 2; i <= mq.index; i++ {
        mq.data[i-1] = mq.data[i]
    }
    mq.index--

    return msg
}

func main() {
    mq := NewMessageQueue()

    mq.Enqueue("hello")
    mq.Enqueue("world")
    mq.Enqueue("golang")

    fmt.Println(mq.Dequeue())
    fmt.Println(mq.Dequeue())
    fmt.Println(mq.Dequeue())
    fmt.Println(mq.Dequeue())
}
Copy after login

Among them, the NewMessageQueue() function is used to initialize an empty MessageQueue object, the Enqueue() function is used to add a message to the message queue, and the Dequeue() function is used to obtain A message in the message queue. In the main() function, we first add 3 messages to the message queue, then output them in sequence, and finally output a non-existent message.

Summary

GolangMap is a data structure in Golang that can be used to store key-value pairs. In practical applications, GolangMap can be used to solve many practical problems, such as counting the number of word occurrences, implementing caching, implementing message queues, etc. This article introduces the basic usage of GolangMap and several practical application examples. I hope it will be helpful to Golang learners.

The above is the detailed content of Understand and apply examples of GolangMap. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
24
How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

See all articles