搜尋
首頁後端開發Golang在 Golang 中安全使用 Map:宣告和初始化的差異

Safely using Maps in Golang: Differences in declaration and initialization

介紹

本週,我正在為 golang 開發一個 API 包裝器包,它處理發送帶有 URL 編碼值的 post 請求、設定 cookie 以及所有有趣的東西。但是,當我建立主體時,我使用 url.Value 類型來建立主體,並使用它來新增和設定鍵值對。然而,我在某些部分遇到了有線零指標引用錯誤,我認為這是因為我手動設定的一些變數造成的。然而,透過仔細調試,我發現了一個常見的陷阱或不好的做法,即僅聲明類型但初始化它,從而導致零引用錯誤。

在這篇文章中,我將介紹什麼是映射、如何建立映射,特別是如何正確宣告和初始化它們。在 golang 中的對應或任何類似資料類型的宣告和初始化之間建立適當的區別。

Golang 中的地圖是什麼?

golang中的map或hashmap是一種基本資料類型,允許我們儲存鍵值對。在底層,它是一個類似標頭映射的資料結構,用於保存儲存桶,這些儲存桶基本上是指向儲存桶數組(連續記憶體)的指標。它具有儲存實際鍵值對的雜湊碼,以及在當前鍵數量溢出時指向新儲存桶的指標。這是一個非常聰明的資料結構,提供幾乎恆定的時間存取。

如何在 Golang 中建立地圖

要在 golang 中建立一個簡單的映射,您可以使用字串和整數的映射作為字母頻率計數器的範例。地圖會將字母儲存為鍵,將它們的頻率儲存為值。

雷雷 雷雷

因此,透過將地圖初始化為map[string]int{},您將得到一個空地圖。然後,這可以用於填充鍵和值,我們迭代字串,對於每個字元(符文),我們將該字元位元組轉換為字串並遞增值,int 的零值為0,因此預設情況下如果密鑰不存在,則其值為零,但這是一把雙刃劍,我們永遠不知道地圖中存在值為0 的密鑰,或者密鑰不存在但預設值為0。為此,您需要檢查該密鑰是否存在於地圖中。

更多詳情,您可以查看我的 Golang Maps 貼文詳細內容。

聲明和初始化之間的區別

在程式語言中宣告和初始化任何變數都是不同的,並且必須在底層類型的實作上做更多的事情。對於 int、string、float 等主要資料類型,有預設值/零值,因此這與變數的宣告和初始化相同。然而,在映射和切片的情況下,聲明只是確保變數可用於程式的範圍,但是對於初始化來說,是將其設定為其預設值/零值或應分配的實際值。

因此,宣告只是使變數在程式範圍內可用。對於映射和切片,聲明變數而不初始化會將其設為 nil,這意味著它指向沒有分配的內存,並且不能直接使用。

而初始化會分配記憶體並將變數設為可用狀態。對於映射和切片,您需要使用 myMap = make(map[keyType]valueType) 或 slice = []type{} 等語法明確初始化它們。如果沒有此初始化,嘗試使用映射或切片將導致運行時錯誤,例如在存取或修改 nil 映射或切片時出現恐慌。

讓我們看看宣告/初始化/未初始化時映射的值。

假設您正在建立一個從地圖讀取設定的組態管理員。地圖將在全域聲明,但僅在載入配置時初始化。

  1. 已宣告但未初始化

下面的程式碼演示了未初始化的地圖訪問。

雷雷 雷雷
  1. 同時宣告與初始化

下面的程式碼示範了同時初始化的地圖存取。

雷雷 雷雷
  1. 宣告並稍後初始化

下面的程式碼示範了稍後初始化的地圖訪問。

package main

import (
    "fmt"
    "log"
)

// Global map to store configuration settings
var configSettings map[string]string // declared but not initialized

func main() {
    // Initialize configuration settings
    initializeConfigSettings()
    // if the function is not called, the map will be nil

    // Get a configuration setting safely
    serverPort := getConfigSetting("server_port")
    fmt.Printf("Server port: %s\n", serverPort)
}

func initializeConfigSettings() {
    if configSettings == nil {
        configSettings = make(map[string]string) // Properly initialize the map
        configSettings["server_port"] = "8080"
        configSettings["database_url"] = "localhost:5432"
        fmt.Println("Configuration settings initialized")
    }
}

func getConfigSetting(key string) string {
    if configSettings == nil {
        log.Fatal("Configuration settings map is not initialized")
    }
    value, exists := configSettings[key]
    if !exists {
        return "Setting not found"
    }
    return value
}
$ go run main.go
Configuration settings initialized
Server port: 8080

In the above code, we declared the global map configSettings but didn't initialize it at that point, until we wanted to access the map. We initialize the map in the main function, this main function could be other specific parts of the code, and the global variable configSettings a map from another part of the code, by initializing it in the required scope, we prevent it from causing nil pointer access errors. We only initialize the map if it is nil i.e. it has not been initialized elsewhere in the code. This prevents overriding the map/flushing out the config set from other parts of the scope.

Pitfalls in access of un-initialized maps

But since it deals with pointers, it comes with its own pitfalls like nil pointers access when the map is not initialized.

Let's take a look at an example, a real case where this might happen.

package main

import (
    "fmt"
    "net/url"
)

func main() {
        var vals url.Values
        vals.Add("foo", "bar")
        fmt.Println(vals)
}

This will result in a runtime panic.

$ go run main.go
panic: assignment to entry in nil map

goroutine 1 [running]:
net/url.Values.Add(...)
        /usr/local/go/src/net/url/url.go:902
main.main()
        /home/meet/code/playground/go/main.go:10 +0x2d
exit status 2

This is because the url.Values is a map of string and a list of string values. Since the underlying type is a map for Values, and in the example, we only have declared the variable vals with the type url.Values, it will point to a nil reference, hence the message on adding the value to the type. So, it is a good practice to use make while declaring or initializing a map data type. If you are not sure the underlying type is map then you could use Type{} to initialize an empty value of that type.

package main

import (
    "fmt"
    "net/url"
)

func main() {
        vals := make(url.Values)
        // OR
        // vals := url.Values{}
        vals.Add("foo", "bar")
        fmt.Println(vals)
}
$ go run urlvals.go
map[foo:[bar]]
foo=bar

It is also recommended by the golang team to use the make function while initializing a map. So, either use make for maps, slices, and channels, or initialize the empty value variable with Type{}. Both of them work similarly, but the latter is more generally applicable to structs as well.

Conclusion

Understanding the difference between declaring and initializing maps in Golang is essential for any developer, not just in golang, but in general. As we've explored, simply declaring a map variable without initializing it can lead to runtime errors, such as panics when attempting to access or modify a nil map. Initializing a map ensures that it is properly allocated in memory and ready for use, thereby avoiding these pitfalls.

By following best practices—such as using the make function or initializing with Type{}—you can prevent common issues related to uninitialized maps. Always ensure that maps and slices are explicitly initialized before use to safeguard against unexpected nil pointer dereferences

Thank you for reading this post, If you have any questions, feedback, and suggestions, feel free to drop them in the comments.

Happy Coding :)

以上是在 Golang 中安全使用 Map:宣告和初始化的差異的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Debian OpenSSL有哪些漏洞Debian OpenSSL有哪些漏洞Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

您如何使用PPROF工具分析GO性能?您如何使用PPROF工具分析GO性能?Mar 21, 2025 pm 06:37 PM

本文解釋瞭如何使用PPROF工具來分析GO性能,包括啟用分析,收集數據並識別CPU和內存問題等常見的瓶頸。

您如何在GO中編寫單元測試?您如何在GO中編寫單元測試?Mar 21, 2025 pm 06:34 PM

本文討論了GO中的編寫單元測試,涵蓋了最佳實踐,模擬技術和有效測試管理的工具。

如何編寫模擬對象和存根以進行測試?如何編寫模擬對象和存根以進行測試?Mar 10, 2025 pm 05:38 PM

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

如何定義GO中仿製藥的自定義類型約束?如何定義GO中仿製藥的自定義類型約束?Mar 10, 2025 pm 03:20 PM

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

解釋GO反射軟件包的目的。您什麼時候使用反射?績效有什麼影響?解釋GO反射軟件包的目的。您什麼時候使用反射?績效有什麼影響?Mar 25, 2025 am 11:17 AM

本文討論了GO的反思軟件包,用於運行時操作代碼,對序列化,通用編程等有益。它警告性能成本,例如較慢的執行和更高的內存使用,建議明智的使用和最佳

如何使用跟踪工具了解GO應用程序的執行流?如何使用跟踪工具了解GO應用程序的執行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化

您如何在GO中使用表驅動測試?您如何在GO中使用表驅動測試?Mar 21, 2025 pm 06:35 PM

本文討論了GO中使用表驅動的測試,該方法使用測試用例表來測試具有多個輸入和結果的功能。它突出了諸如提高的可讀性,降低重複,可伸縮性,一致性和A

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。