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()函数在控制台打印数组。
例子
Golang程序使用for循环和主函数中的make函数来填充数组中的特定元素
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:在外部函数中使用制作函数和for循环
在这个方法中,我们将看到如何使用一个外部函数将一个数组填入一个特定的元素。这个函数把数组的大小和特定的元素作为它的参数。在Golang中使用print语句将输出结果打印在屏幕上。
算法
第1步 - 在程序中声明一个包main和导入fmt包。
第2步 - 创建一个函数print_specific,其参数为数组的大小和特定元素。
第 3 步 – 使用make函数在该函数中创建一个数组,数组的大小和空数组作为其参数。
第 4 步 – 运行一个循环直到数组的长度,并为数组的每个索引分配一个特定的值。
第 5 步 – 赋值完成后,将数组返回到函数print_specific。
第6步 - 该函数被main函数进一步调用并在fmt.Println()函数的帮助下打印出来。
例子
Golang程序使用make函数和外部函数的for循环来填充一个具有特定元素的数组
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]
总结
我们用两种方法执行了用特定元素填充数组的程序。在第一种方法中,我们使用main方法来填充数组中的元素;在第二种方法中,我们使用外部函数方法,其中数组的大小和特定的元素被作为参数通过main函数传递。在这两种情况下都得到了类似的输出。因此,程序成功执行。
极客教程