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
+25.9k Golang : How to read integer value from standard input ?
+21.9k Golang : Convert string slice to struct and access with reflect example
+8.9k Golang : HTTP Routing with Goji example
+5.4k Golang : What is StructTag and how to get StructTag's value?
+13.4k Golang : Read from buffered reader until specific number of bytes
+9.7k Golang : Populate slice with sequential integers example
+8.1k Golang : HTTP Server Example
+17.4k Golang : Check if IP address is version 4 or 6
+12.7k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+7.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+19.9k Golang : Count JSON objects and convert to slice/array
+36k Golang : Get file last modified date and time