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.