- Go Systems Programming
- Mihalis Tsoukalos
- 288字
- 2021-07-02 18:07:59
Converting an array into a map
This subsection will perform a practical operation, which is converting an array into a map without knowing the size of array in advance. The Go code of array2map.go can be divided into three main parts. The first part is the standard Go code that includes the required packages and the beginning of the main() function:
package main import ( "fmt" "strconv" ) func main() {
The second part, which implements the core functionality, is as follows:
anArray := [4]int{1, -2, 14, 0} aMap := make(map[string]int) length := len(anArray) for i := 0; i < length; i++ { fmt.Printf("%s ", strconv.Itoa(i)) aMap[strconv.Itoa(i)] = anArray[i] }
You first define the array variable and the map variable you will use. The for loop is used for visiting all the array elements and adding them to map. The strconv.Itoa() function converts the index number of array into a string.
The last part, which is just for printing the contents of the generated map, uses the expected range form of the for loop:
for key, value := range aMap {
fmt.Printf("%s: %d\n", key, value) } }
As you can easily guess, developing the inverse operation is not always possible because map is a richer data structure than array. However, the price you pay for a more powerful data structure is time because array operations are usually faster.
- UML和模式應用(原書第3版)
- Monkey Game Development:Beginner's Guide
- 算法精粹:經典計算機科學問題的Java實現
- Java從入門到精通(第4版)
- Python應用輕松入門
- Building Mapping Applications with QGIS
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- MySQL數據庫管理與開發實踐教程 (清華電腦學堂)
- 數據結構(C語言)
- Visual Basic學習手冊
- Salesforce Reporting and Dashboards
- Node.js 12實戰
- SignalR:Real-time Application Development(Second Edition)
- 現代C:概念剖析和編程實踐
- 零基礎學Java第2版