搜尋
首頁後端開發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
掌握GO弦:深入研究'字符串”包裝掌握GO弦:深入研究'字符串”包裝May 12, 2025 am 12:05 AM

你應該關心Go語言中的"strings"包,因為它提供了處理文本數據的工具,從基本的字符串拼接到高級的正則表達式匹配。 1)"strings"包提供了高效的字符串操作,如Join函數用於拼接字符串,避免性能問題。 2)它包含高級功能,如ContainsAny函數,用於檢查字符串是否包含特定字符集。 3)Replace函數用於替換字符串中的子串,需注意替換順序和大小寫敏感性。 4)Split函數可以根據分隔符拆分字符串,常用於正則表達式處理。 5)使用時需考慮性能,如

GO中的'編碼/二進制”軟件包:您的二進制操作首選GO中的'編碼/二進制”軟件包:您的二進制操作首選May 12, 2025 am 12:03 AM

“編碼/二進制”軟件包interingoisentialForHandlingBinaryData,oferingToolSforreDingingAndWritingBinaryDataEfficely.1)Itsupportsbothlittle-endianandBig-endianBig-endianbyteorders,CompialforOss-System-System-System-compatibility.2)

Go Byte Slice操縱教程:掌握'字節”軟件包Go Byte Slice操縱教程:掌握'字節”軟件包May 12, 2025 am 12:02 AM

掌握Go語言中的bytes包有助於提高代碼的效率和優雅性。 1)bytes包對於解析二進制數據、處理網絡協議和內存管理至關重要。 2)使用bytes.Buffer可以逐步構建字節切片。 3)bytes包提供了搜索、替換和分割字節切片的功能。 4)bytes.Reader類型適用於從字節切片讀取數據,特別是在I/O操作中。 5)bytes包與Go的垃圾回收器協同工作,提高了大數據處理的效率。

您如何使用'字符串”軟件包在GO中操縱字符串?您如何使用'字符串”軟件包在GO中操縱字符串?May 12, 2025 am 12:01 AM

你可以使用Go語言中的"strings"包來操縱字符串。 1)使用strings.TrimSpace去除字符串兩端的空白字符。 2)用strings.Split將字符串按指定分隔符拆分成切片。 3)通過strings.Join將字符串切片合併成一個字符串。 4)用strings.Contains檢查字符串是否包含特定子串。 5)利用strings.ReplaceAll進行全局替換。注意使用時要考慮性能和潛在的陷阱。

如何使用'字節”軟件包在GO中操縱字節切片(逐步)如何使用'字節”軟件包在GO中操縱字節切片(逐步)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

Go Bytes軟件包:有什麼選擇?Go Bytes軟件包:有什麼選擇?May 11, 2025 am 12:11 AM

thealternativestogo'sbytespackageincageincludethestringspackage,bufiopackage和customstructs.1)thestringspackagecanbeusedforbytemanipulationforbytemanipulationbybyconvertingbytestostostostostostrings.2))

操縱字節切片在GO:'字節”軟件包的功能操縱字節切片在GO:'字節”軟件包的功能May 11, 2025 am 12:09 AM

“字節”包裝封裝forefforeflyManipulatingByteslices,CocialforbinaryData,網絡交易和andfilei/o.itoffersfunctionslikeIndexForsearching,BufferForhandLinglaRgedLargedLargedAtaTasets,ReaderForsimulatingStreamReadReadImreAmreadReamReadinging,以及Joineffiter和Joineffiter和Joineffore

Go Strings套餐:弦樂操縱的綜合指南Go Strings套餐:弦樂操縱的綜合指南May 11, 2025 am 12:08 AM

go'sstringspackageIscialforficientficientsTringManipulation,uperingToolSlikestrings.split(),strings.join(),strings.replaceall(),andStrings.contains.contains.contains.contains.contains.contains.split.split(split()strings.split()dividesStringoSubSubStrings; 2)strings.joins.joins.joinsillise.joinsinelline joinsiline joinsinelline; 3);

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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中