Golang 从哈希集合中获取键

Golang 从哈希集合中获取键

哈希集合是一种在Go中包含键值对并允许快速查找、添加和删除的数据结构。通过将键哈希为索引,可以访问与键对应的值。在Go中,以图的形式存在哈希集合具有内建的支持。在这个示例中,map是一种引用类型,通过使用map关键字,后面跟着键类型和值类型的格式来声明。在这个示例中,我们将使用两种方法从哈希集合中获取键,第一个示例中我们将使用append方法从哈希集合中获取键,第二个方法中我们将使用索引变量。让我们深入示例中,看看我们如何实现。

语法

func make ([] type, size, capacity)

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

func append(slice, element_1, element_2…, element_N) []T

append函数用于向数组切片中添加值。它接受多个参数。第一个参数是我们希望添加值的数组,其后是要添加的值。然后,函数返回包含所有值的最终数组切片。

步骤

  • 在程序中导入所需的包

  • 创建一个主函数

  • 在主函数中,利用内部函数从哈希集合中获取键

  • 使用fmt包将地图的键打印到终端上

示例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]

结论

我们使用两个示例来执行从哈希集合中获取键的程序。在第一个示例中,我们使用了Golang中的内置函数append,将哈希映射的键添加到名为keys的切片中;在第二个示例中,我们使用了一个索引变量来执行类似的操作。这两个示例都给出了预期的输出结果。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程