How could I write a function to print a map object in Go (Golang)? Right now I have this, but it doesn't compile. It returns cannot convert value (type interface {}) to type reflect.Kind: need type assertion
.
package main
type MyDictionary map[string]interface{}
func (d MyDictionary) String() string {
var stringBuffer bytes.Buffer
for key, value := range d {
stringBuffer.WriteString(key)
stringBuffer.WriteString(": ")
valueType := reflect.Kind(value)
switch valueType {
case reflect.String:
log.Println("string") // just to check if this block gets executed
// Add to stringBuffer
case reflect.Float64:
log.Println("float64") // just to check if this block gets executed
// Add to stringBuffer
default:
log.Println("Error: type was", valueType)
}
}
return stringBuffer.String()
}
func main() {
var dict MyDictionary = make(MyDictionary)
dict["hello"] = "world"
dict["floating"] = 10.0
dict["whole"] = 12
fmt.Println(dict)
}
I want String()
to return a string like hello: world
floating: 10.0
whole: 12
. That I can then pass to fmt.Println()
to print this. In Java, I would use StringBuilder
for this.
hello: world
floating: 10.0
whole: 12
I also tried switching on value.(type)
with case string:
and case float64
, but then I didn't know how to write those values to stringBuffer
.