Go 語言程式:向雜湊集合新增元素


在 Go 語言中,我們可以使用簡單的索引方法和切片方法將元素新增到雜湊集合中。雜湊函式用於檢索和儲存資料。本文將介紹兩個不同的示例,我們將使用上述方法在 Go 程式語言中將元素新增到雜湊集合中。

語法

func make ([] type, size, capacity)

Go 語言中的 make 函式用於建立陣列/對映,它接受要建立的變數型別、大小和容量作為引數。

演算法

  • 在程式中匯入所需的包

  • 建立 main 函式

  • 在 main 函式中建立一個雜湊對映並在雜湊對映中新增元素

  • 在控制檯上列印對映

示例 1

在這個示例中,我們將使用 Go 語言中的 make 函式建立一個雜湊對映,並使用索引將值新增到該雜湊對映中。我們將使用 fmt 包在控制檯上列印雜湊對映。

//Golang program to add items into the hash collection
package main
   
//import fmt package
import "fmt"  
   
//Main function to execute the program
func main() {
   
   // create an empty map to hold key-value pairs
   hashmap := make(map[string]int)
   
   // add key-value pairs to the map
   hashmap["pencil"] = 10
   hashmap["pen"] = 20
   hashmap["scale"] = 15
   
   // print the map to see its contents
   fmt.Println("The map after values are added in it is presented as follows:")
   fmt.Println(hashmap)
}

輸出

The map after values are added in it is presented as follows:
map[pen:20 pencil:10 scale:15]

示例 2

在本例中,我們將建立一個與上一個示例中建立的類似的雜湊對映,此外,我們將使用 struct 關鍵字建立一個切片,然後使用 for 迴圈從該切片中將鍵值對新增到對映中。輸出將是一個使用 fmt 包列印的對映。

//Golang program to add items into the hash collection
package main
   
//import fmt package
import "fmt"   
   
//Main function to execute the program
func main() {
   
   // create an empty map using the make() function
   hashmap := make(map[string]int)
   
   // create a slice of key-value pairs to add to the map
   keyvaluepairs := []struct {
      key   string
      value int
   }{
      {"pencil", 10},
      {"pen", 20},
      {"scale", 15},
   }
   
   // loop over the slice and add the key-value pairs to the map
   for _, pair := range keyvaluepairs {
      hashmap[pair.key] = pair.value
   }
   
   // print the map to see its contents
   fmt.Println("The hashmap after data is added in it is presented as follows:")
   fmt.Println(hashmap)
}

輸出

The hashmap after data is added in it is presented as follows:
map[pen:20 pencil:10 scale:15]

結論

透過兩個示例,我們執行了將元素新增到雜湊集合的程式。在第一個示例中,我們使用索引將元素新增到雜湊對映中,然後在控制檯上列印它,然後在第二個示例中,我們使用切片將值新增到對映中。

更新於: 2023年3月27日

184 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.