Go 語言程式:從雜湊集合中獲取鍵
在 Go 語言中,雜湊集合是一種包含鍵值對的資料結構,它能夠快速查詢、新增和刪除元素。透過將鍵雜湊到索引中可以訪問對應於鍵的值。Go 語言內建支援以 map 形式存在的雜湊集合。這裡,map 是一種引用型別,其宣告方式是使用 map 關鍵字,後跟鍵型別和值型別,格式為 `map[KeyType]ValueType`。在本例中,我們將使用兩種方法從雜湊集合中獲取鍵:第一種方法使用 append 函式從雜湊對映中獲取鍵;第二種方法使用索引變數。讓我們透過示例來了解如何實現。
語法
func make ([] type, size, capacity)
Go 語言中的 make 函式用於建立陣列/map,它接受要建立的變數型別、大小和容量作為引數。
func append(slice, element_1, element_2…, element_N) []T
append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。
演算法
匯入程式中所需的包
建立一個 main 函式
在 main 函式中,藉助內部函式從雜湊集合中獲取鍵
使用 fmt 包在終端上列印 map 的鍵
示例 1
在這個例子中,我們將建立一個雜湊對映和一個鍵切片。我們將迭代雜湊對映,並將鍵新增到鍵切片中,然後使用 fmt 包的 Println() 函式在控制檯上列印這些鍵。讓我們來看一下程式碼和演算法,瞭解執行過程。
//Golang program to get keys from a hash collection package main import "fmt" //Main function to execute the program func main() { hashmap := map[string]int{ //create a hashmap using map literal "apple": 10, "mango": 20, "banana": 30, //assign the values to the key } keys := make([]string, 0, len(hashmap)) //create a keys slice similar to the length of the hashmap for key := range hashmap { keys = append(keys, key) //append the key from hashmap to keys } fmt.Println("The keys obtained here from hash collection are:") fmt.Println(keys) //print the slice on the console }
輸出
The keys obtained here from hash collection are: [mango banana apple]
示例 2
在這種方法中,我們將建立一個雜湊對映,並使用一個額外的索引變數在鍵切片中獲取其鍵。我們將迭代雜湊對映,並在每次迭代中將雜湊對映中的鍵新增到鍵切片中,並使用 fmt 包在控制檯上列印它。讓我們來看一下程式碼和演算法來理解這個概念。
//Golang program to get keys from a hash collection package main import "fmt" //Main function to execute the program func main() { hashmap := map[string]int{ "apple": 10, "mango": 20, "banana": 30, } keys := make([]string, len(hashmap)) //create keys slice to store the keys of hashmap i := 0 for key := range hashmap { keys[i] = key //in the keys slice add the key on every iteration i++ } fmt.Println("The keys obtained from the hash collection is:") fmt.Println(keys) //print the keys on the console }
輸出
The keys obtained from the hash collection is: [apple mango banana]
結論
我們透過兩個例子演示瞭如何從雜湊集合中獲取鍵的程式。在第一個例子中,我們使用了 Go 語言中內建的 append 函式將雜湊對映中的鍵新增到名為 keys 的切片中;在第二個例子中,我們使用索引變數執行了類似的操作。兩個例子都得到了預期的輸出。