Golang 填充数组
在本教程中,我们将学习如何用特定元素填充数组。我们将探索几个示例,以了解更多关于此程序的信息。输出将使用fmt.Println()函数打印在控制台上。让我们来看看并了解该程序。
我们在示例中使用了以下make()函数。
语法
func make ([] type, size, capacity)
在Go语言中, make 函数用于创建数组/映射,它接受要创建的变量的类型、大小和容量作为参数。
方法1:在主函数中使用for循环和make函数
在此方法中,我们将看到如何使用for循环将特定元素分配给数组。让我们深入算法和代码,以清晰地了解这种方法。
步骤
步骤1 - 在程序中声明一个main包并导入fmt包。
步骤2 - 创建一个main函数,并使用make函数创建一个数组,并将数组的大小设置为6。
步骤3 - 运行循环,直到数组的长度,并为每个数组索引分配一个特定的值。
步骤4 - 在值分配后,使用fmt.Println()函数在控制台打印数组。
示例
使用for循环和make函数在主函数中将数组填充为特定元素的Golang程序。
package main
import (
"fmt"
)
func main() {
arr := make([]int, 6)
//creating array using make function
for index := range arr {
arr[index] = 60
//assign the specific element to the array indexes
}
fmt.Println("The specific element to be added in array is:", 60)
fmt.Println("The array with the specific element is:", arr)
}
输出
The specific element to be added in array is: 60
The array with the specific element is: [60 60 60 60 60 60]
方法2:使用外部函数中的Make函数和for循环
在这种方法中,我们将看到如何使用外部函数填充一个特定元素的数组。函数的参数是数组的大小和特定元素。输出使用Golang的print语句打印在屏幕上。
步骤
步骤1 - 在程序中声明package main,并导入fmt包。
步骤2 - 创建一个名为print_specific的函数,其参数是数组的大小和特定元素。
步骤3 - 在函数内部使用make函数创建一个数组,其参数是数组的大小和空数组。
步骤4 - 运行一个循环,直到数组的长度,并将特定的值赋给数组的每个索引。
步骤5 - 值被赋予后,将数组返回给print_specific函数。
步骤6 - main函数进一步调用该函数,并使用fmt.Println()函数在那里进行打印。
示例
使用make函数和for循环在外部函数中填充数组的Golang程序。
package main
import (
"fmt"
)
func print_specific(size, specific int) []int {
//creating function
arr := make([]int, size)
for i := range arr {
arr[i] = specific
//assign specific element to the array indexes
}
return arr
}
func main() {
arr := print_specific(6,20)
// call the function with size of array and the specific element
fmt.Println("The specific element to be added in array is:", 20)
fmt.Println("The array with a specific element is:")
fmt.Println(arr)
}
输出
The specific element to be added in array is: 20
The array with a specific element is:
[20 20 20 20 20 20]
结论
我们用两种方法执行了用特定元素填充数组的程序。在第一种方法中,我们使用了主要的方法来填充数组中的元素,在第二种方法中,我们使用了外部函数的方法,通过主函数将数组的大小和特定元素作为参数传递。在两种情况下都获得了类似的输出。因此程序执行成功。