Go 語言程式:將雜湊集合轉換為陣列
在 Go 程式語言中,雜湊集合包含一個雜湊對映,該對映以鍵值對的形式儲存值。在本程式中,我們將把該對映轉換為陣列,陣列具有固定大小,可以透過索引訪問。我們將使用兩個示例來執行該程式。在第一個示例中,我們將使用索引變數將值新增到陣列中,在第二個示例中,我們將使用追加方法將值新增到陣列中。
語法
func make ([] type, size, capacity)
Go 語言中的 make 函式用於建立陣列/對映,它接受要建立的變數型別、其大小和容量作為引數。
func append(slice, element_1, element_2…, element_N) []T
append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要向其新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。
演算法
建立一個 package main 並宣告程式中的 fmt(格式化包),其中 main 生成可執行程式碼,而 fmt 幫助格式化輸入和輸出。
使用對映字面量建立雜湊對映,其鍵和值均為字串型別。
在此步驟中,使用 make 函式(Go 語言中的內建函式)建立與雜湊對映長度相同的陣列。
建立一個 I 變數並將其初始化為 0,然後在雜湊對映上執行迴圈,並在每次迭代中將陣列索引分配雜湊對映中的值。
在每次迭代中遞增第 i 個變數,並且在迴圈終止後在控制檯上列印陣列。
列印語句使用 fmt 包中的 Println() 函式執行,其中 ln 表示換行。
示例 1
在此示例中,我們將使用對映字面量建立一個雜湊對映,其中鍵和值均為字串。然後建立一個空陣列,其中將使用索引變數新增雜湊對映中的值,然後使用 fmt 包在控制檯上列印陣列。
package main import "fmt" //Main function to execute the program func main() { // create a hash collection hashmap := map[string]string{ "item1": "value1", "item2": "value2", "item3": "value3", } // create an array to add the values from map array := make([]string, len(hashmap)) // iterate over the keys of the hash collection and store the corresponding values in the array i := 0 for _, value := range hashmap { array[i] = value i++ } // print the array on the terminal fmt.Println("The hash collection conversion into array is shown as:") fmt.Println(array) }
輸出
The hash collection conversion into array is shown as: [value1 value2 value3]
示例 2
在此示例中,我們將像在上一方法中一樣建立一個雜湊對映,以及一個字串型別的陣列來儲存對映的值,然後迭代對映並使用 append 方法(Go 語言中的內建方法)將值新增到陣列中。
package main import "fmt" //Main function to execute the program func main() { // create a hash collection hashmap := map[string]string{ "item1": "value1", "item2": "value2", "item3": "value3", } // create an empty array in which values will be added from hash collection array := []string{} // iterate over the keys of the hash collection and append the corresponding values to the array for key := range hashmap { value := hashmap[key] array = append(array, value) } // print the resulting array fmt.Println("The conversion of the hash collection into array is shown like:") fmt.Println(array) }
輸出
The conversion of the hash collection into array is shown like: [value1 value2 value3]
結論
我們使用兩個示例執行了將雜湊集合轉換為陣列的程式。在這兩個示例中,我們都建立了空陣列來儲存對映的值,但在第一個示例中,我們使用了 i 變數和索引來新增值,在第二個示例中,我們使用了 append 方法來新增陣列中的值。這兩個示例都返回了類似的輸出。