Golang : Array mapping with Interface
New comers to Golang often have slight difficulty understanding how interface works in Golang. This is a simple tutorial to demonstrate how to map arrays with interface.
package main
import (
"fmt"
)
var strArray = []string{"abc", "def", "ghi"}
var strMap = map[string]interface{}{}
var intArray = []int{1, 2, 3}
var intMap = map[int]string{}
func main() {
for i := 0; i != 3; i++ {
fmt.Println(intArray[i], "\t", strArray[i])
intMap[i] = strArray[i]
strMap[strArray[i]] = intMap
}
fmt.Println("String map : ", strMap)
fmt.Println("Integer map : ", intMap)
}
Output :
1 abc
2 def
3 ghi
String map : map[ghi:map[0:abc 1:def 2:ghi] abc:map[0:abc 1:def 2:ghi] def:map[0:abc 1:def 2:ghi]]
Integer map : map[0:abc 1:def 2:ghi]
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.4k Golang : Convert string slice to struct and access with reflect example
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+12.9k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.9k How to show different content from website server when AdBlock is detected?
+25.4k Golang : How to write CSV data to file
+8.2k Golang : Generate Datamatrix barcode
+39.7k Golang : UDP client server read write example
+12.2k Elastic Search : Return all records (higher than default 10)
+5.1k Golang : Pad file extension automagically
+10.3k Golang : Create matrix with Gonum Matrix package example
+5.3k Golang : Stop goroutine without channel