使用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]
結論
我們使用兩種方法執行了使用特定元素填充陣列的程式。在第一種方法中,我們使用了主要方法來填充陣列中的元素,在第二種方法中,我們使用了外部函式方法,其中陣列的大小和特定元素作為引數透過主函式傳遞。兩種情況下都獲得了相似的輸出。因此程式成功執行。