官术网_书友最值得收藏!

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.

Bear in mind that if you know that all the keys of a map will be consecutive positive integer numbers, you might consider using an array or a slice instead of a map . In fact, even if the keys are not consecutive, arrays and slices are cheaper data structures than maps, so you might end up with a sparse matrix.

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.

主站蜘蛛池模板: 弋阳县| 乐山市| 前郭尔| 黄陵县| 萨嘎县| 稷山县| 陵川县| 册亨县| 马山县| 淮滨县| 阿尔山市| 饶平县| 红安县| 合江县| 清水河县| 洛浦县| 乐至县| 监利县| 富阳市| 尤溪县| 修水县| 建瓯市| 巢湖市| 永修县| 额济纳旗| 樟树市| 南陵县| 景德镇市| 礼泉县| 丰台区| 宁晋县| 巨鹿县| 临朐县| 九台市| 建始县| 安新县| 当阳市| 望谟县| 紫云| 防城港市| 锦州市|