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 的切片中;在第二个例子中,我们使用索引变量执行了类似的操作。两个例子都得到了预期的输出。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP