I (golang newbie) am trying to create a map[string]interfaces{} in a function. The code compiles and runs but the map is empty.
package main
import (
"fmt"
"encoding/json"
)
func main() {
var f interface{}
var sJson string // JSON string from VT
var err error // errors
var b []byte // bytearray of JSON string
var rootMap map[string]interface{}
rootMap = make(map[string]interface{})
sJson=`{"key": "foo"}`
fmt.Println(sJson)
err = json2map(&b, &sJson, f, rootMap)
if err != nil { return }
switch v := rootMap["key"].(type) {
case float64:
fmt.Printf("Value: %d",v)
case string:
fmt.Printf("Value: %s", v)
case nil:
fmt.Println("key is nil")
default:
fmt.Println("type is unknown")
}
}
func json2map(b *[]byte, sJson *string, f interface{}, myMap map[string]interface{}) error {
var err error
*b = []byte(*sJson)
err = json.Unmarshal(*b,&f)
myMap = f.(map[string]interface{})
return err
}
The output is:
{"key": "foo"}
key is nil
I found this article which describes how to use map[string]string. This code works as expected:
package main
import (
"fmt"
)
type MyType struct {
Value1 int
Value2 string
}
func main() {
myMap := make(map[string]string)
myMap["key"] = "foo"
ChangeMyMap(myMap)
fmt.Printf("Value : %s
", myMap["key"])
}
func ChangeMyMap(TheMap map[string]string) {
TheMap["key"] = "bar"
}
So I think my problem has to do with the map being of type interface instead of string but I cannot tell why the first code doesn't work, while the 2nd does.