Go语言程序:将切片转换为数组


切片也可以称为动态数组,因为它的值是动态的,而普通数组是静态的。这使得切片更高效、更快。它们是按引用传递而不是按值传递。在这里,我们将学习使用各种示例将切片转换为数组的不同技术。

语法

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

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

func copy(dst, str[] type) int

Go语言中的 copy 函数用于将一个源数组的值复制到目标数组,并将复制的元素数量作为结果返回。它以两个数组作为参数。

算法

  • 步骤 1 - 创建一个 main 包,并在程序中声明 fmt(格式化包),其中 main 生成可执行代码,fmt 帮助格式化输入和输出。

  • 步骤 2 - 创建一个切片,并使用 append 函数向切片中添加一些值。

  • 步骤 3 - 初始化一个指定大小的数组,以便可以将值复制到其中。

  • 步骤 4 - 使用 copy 函数将切片的元素复制到数组中。

  • 步骤 5 - 使用 fmt.Println() 函数在控制台上打印数组,其中 ln 表示换行。

示例 1

在这个示例中,我们将学习如何使用内置函数 copy 将切片转换为数组。在这里,我们将把切片元素复制到创建的数组中。让我们深入研究代码和算法,看看它是如何完成的。

package main
import "fmt"

//create main function to execute the program
func main() {
   var slice []int // initialize slice
   slice = append(slice, 10) //fill the slice using append function
   slice = append(slice, 20)
   slice = append(slice, 30)
   
   // Convert the slice to an array
   array := [3]int{} //initialized an empty array
   copy(array[:], slice) //copy the elements of slice in newly created array
   fmt.Println("The slice is converted into array and printed as:")
   fmt.Println(array) // prints the output: [10 20 30]
}

输出

The slice is converted into array and printed as:
[10 20 30]

示例 2

在这个示例中,我们将看到如何使用 for 循环将切片转换为数组。切片的元素将被赋值给数组。让我们仔细查看代码,使我们的概念清晰明了。

package main
import "fmt"

//create main function to execute the program
func main() {
   var slice []int // initialize slice
   slice = append(slice, 10) //fill the slice using append function
   slice = append(slice, 20)
   slice = append(slice, 30)
   
   // Convert the slice to an array
   var array [3]int
   for i, element := range slice {
      array[i] = element // store slice elements in the newly created array
   }
   fmt.Println("The array is printed after conversion from slice:")
   fmt.Println(array) // prints the output: [1 2 3]
}

输出

The array is printed after conversion from slice:
[10 20 30]

结论

在上面的程序中,我们使用了两个示例将切片转换为数组。在第一个示例中,我们使用了 copy 函数来获得一个数组。在第二个示例中,我们使用了 for 循环,并且在上面的示例中使用了两个内置函数——append 和 copy。Append 用于向切片中添加元素。因此,程序成功执行。

更新于:2023年2月13日

4K+ 次查看

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.