Golang 将哈希集合转换为数组

Golang 将哈希集合转换为数组

在Go编程语言中,哈希集合包含一个散列表,以键值对的形式存储值。在这个特定的程序中,我们将把散列表转换成一个固定大小的数组,并可以通过索引来访问。我们将使用两个示例来执行这个程序。在第一个示例中,我们将使用一个索引变量将值添加到数组中,在第二个示例中,我们将使用append方法将值添加到数组中。

语法

func make ([] type, size, capacity)

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

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

append函数用于将值添加到数组片段中。它接受多个参数。第一个参数是要添加值的数组,其后是要添加的值。函数然后返回包含所有值的最终数组片段。

步骤

  • 创建一个主包,并在程序中声明fmt(格式化包),其中主要生成可执行代码,fmt在格式化输入和输出方面起到帮助作用。

  • 使用映射字面量创建一个哈希映射,其中键和值的类型均为字符串。

  • 在这一步中,使用make函数(Go语言的内置函数)创建一个与哈希映射长度相似的数组。

  • 创建一个I变量并将其初始化为0,然后在哈希映射上运行循环,在每次迭代中,将数组索引分配给哈希映射的值。

  • 在每次迭代中递增ith变量,并在循环结束后将数组打印到控制台。

  • 使用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方法将值添加到数组中,append是Golang中的内置方法。

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方法来添加数组中的值。这两个示例返回相似的输出。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程