使用Golang填充数组特定元素的程序
在本教程中,我们将学习如何使用特定元素填充数组。我们将探讨一些示例以了解更多关于此程序的信息。输出将使用fmt.Println()函数打印到控制台。让我们来看一下并理解程序。
我们在示例中使用了以下make()函数。
语法
func make ([] type, size, capacity)
Go语言中的make函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。
方法一:在主函数中使用for循环和Make函数
在这种方法中,我们将看到如何使用for循环将特定元素分配给数组。让我们深入研究算法和代码,以获得对该方法的清晰理解。
算法
步骤1 - 在程序中声明一个包main并导入fmt包。
步骤2 - 创建一个主函数,并使用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]
方法二:在外置函数中使用Make函数和for循环
在这种方法中,我们将看到如何使用外部函数使用特定元素填充数组。该函数将数组大小和特定元素作为参数。输出使用Golang中的print语句打印到屏幕上。
算法
步骤1 - 在程序中声明一个包main并导入fmt包。
步骤2 - 创建一个print_specific函数,数组大小和特定元素作为其参数。
步骤3 - 使用make函数在函数内创建一个数组,数组大小和空数组作为其参数。
步骤4 - 运行一个循环直到数组长度,并将特定值分配给数组的每个索引。
步骤5 - 分配值后,将数组返回给print_specific函数。
步骤6 - 主函数进一步调用该函数,并在那里借助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]
结论
我们使用两种方法执行了使用特定元素填充数组的程序。在第一种方法中,我们使用了主要方法来填充数组中的元素,在第二种方法中,我们使用了外部函数方法,其中数组的大小和特定元素作为参数通过主函数传递。两种情况下都获得了相似的输出。因此程序成功执行。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP