- 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.
- Building a Home Security System with Raspberry Pi
- Mastering PHP Design Patterns
- Mastering Ext JS
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Learning Vaadin 7(Second Edition)
- Learning OpenCV 3 Computer Vision with Python(Second Edition)
- Python深度學(xué)習(xí)原理、算法與案例
- 從零開(kāi)始學(xué)Python網(wǎng)絡(luò)爬蟲(chóng)
- Python程序設(shè)計(jì)開(kāi)發(fā)寶典
- C語(yǔ)言程序設(shè)計(jì)
- WebStorm Essentials
- Python機(jī)器學(xué)習(xí)開(kāi)發(fā)實(shí)戰(zhàn)
- C# 7.0本質(zhì)論
- PHP程序設(shè)計(jì)高級(jí)教程
- Building Microservices with .NET Core 2.0(Second Edition)