Golang 将项目添加到哈希集合中

Golang 将项目添加到哈希集合中

在 Golang 中,我们可以使用简单的索引方法和切片方法将项目添加到哈希集合中。哈希函数用于检索和存储数据。在本文中,我们将看到两个不同的示例,其中我们将使用上述方法将项目添加到 Golang 编程语言中的哈希集合中。

语法

func make ([] type, size, capacity)

在go语言中,make函数用于创建数组/映射,它接受要创建的变量的类型、大小和容量作为参数。

步骤

  • 在程序中引入所需的包

  • 创建一个主要的函数

  • 在主函数中创建一个哈希映射并向其中添加项

  • 在控制台上打印映射表

示例1

在这个示例中,我们将使用Golang的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]

结论

使用两个示例,我们执行了向哈希集合中添加项的程序。在第一个示例中,我们使用索引将项添加到哈希映射中,然后在控制台上打印出来;在第二个示例中,我们使用切片将值添加到映射中。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程