Go 语言程序:将哈希集合转换为数组
在 Go 编程语言中,哈希集合包含一个哈希映射,该映射以键值对的形式保存值。在本程序中,我们将把该映射转换为数组,数组具有固定大小,可以通过索引访问。我们将使用两个示例来执行该程序。在第一个示例中,我们将使用索引变量将值添加到数组中,在第二个示例中,我们将使用追加方法将值添加到数组中。
语法
func make ([] type, size, capacity)
Go 语言中的 make 函数用于创建数组/映射,它接受要创建的变量类型、其大小和容量作为参数。
func append(slice, element_1, element_2…, element_N) []T
append 函数用于向数组切片添加值。它接受多个参数。第一个参数是要向其添加值的数组,后跟要添加的值。然后,该函数返回包含所有值的最终数组切片。
算法
创建一个 package main 并声明程序中的 fmt(格式化包),其中 main 生成可执行代码,而 fmt 帮助格式化输入和输出。
使用映射字面量创建哈希映射,其键和值均为字符串类型。
在此步骤中,使用 make 函数(Go 语言中的内置函数)创建与哈希映射长度相同的数组。
创建一个 I 变量并将其初始化为 0,然后在哈希映射上运行循环,并在每次迭代中将数组索引分配哈希映射中的值。
在每次迭代中递增第 i 个变量,并且在循环终止后在控制台上打印数组。
打印语句使用 fmt 包中的 Println() 函数执行,其中 ln 表示换行。
示例 1
在此示例中,我们将使用映射字面量创建一个哈希映射,其中键和值均为字符串。然后创建一个空数组,其中将使用索引变量添加哈希映射中的值,然后使用 fmt 包在控制台上打印数组。
package main
import "fmt"
//Main function to execute the program
func main() {
// create a hash collection
hashmap := map[string]string{
"item1": "value1",
"item2": "value2",
"item3": "value3",
}
// create an array to add the values from map
array := make([]string, len(hashmap))
// iterate over the keys of the hash collection and store the corresponding values in the array
i := 0
for _, value := range hashmap {
array[i] = value
i++
}
// print the array on the terminal
fmt.Println("The hash collection conversion into array is shown as:")
fmt.Println(array)
}
输出
The hash collection conversion into array is shown as: [value1 value2 value3]
示例 2
在此示例中,我们将像在上一方法中一样创建一个哈希映射,以及一个字符串类型的数组来保存映射的值,然后迭代映射并使用 append 方法(Go 语言中的内置方法)将值添加到数组中。
package main
import "fmt"
//Main function to execute the program
func main() {
// create a hash collection
hashmap := map[string]string{
"item1": "value1",
"item2": "value2",
"item3": "value3",
}
// create an empty array in which values will be added from hash collection
array := []string{}
// iterate over the keys of the hash collection and append the corresponding values to the array
for key := range hashmap {
value := hashmap[key]
array = append(array, value)
}
// print the resulting array
fmt.Println("The conversion of the hash collection into array is shown like:")
fmt.Println(array)
}
输出
The conversion of the hash collection into array is shown like: [value1 value2 value3]
结论
我们使用两个示例执行了将哈希集合转换为数组的程序。在这两个示例中,我们都创建了空数组来保存映射的值,但在第一个示例中,我们使用了 i 变量和索引来添加值,在第二个示例中,我们使用了 append 方法来添加数组中的值。这两个示例都返回了类似的输出。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP