我怎么能写一个函数来在Go(Golang)中打印一个地图对象?现在我有这个,但它没有编译.它回来了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)
}
Run Code Online (Sandbox Code Playgroud)
我想要String()返回一个字符串hello: world\nfloating: 10.0\nwhole: 12\n.然后我可以传递fmt.Println()打印这个.在Java中,我会用StringBuilder它.
hello: world
floating: 10.0
whole: 12
Run Code Online (Sandbox Code Playgroud)
我也尝试value.(type)使用case string:和case float64,但后来我不知道如何写这些值stringBuffer.
这是一个惯用的解决方案.
func (d MyDictionary) String() string {
var buf bytes.Buffer
for k, v := range d {
buf.WriteString(k + ": ")
// v is an interface{} here
switch v := v.(type) {
// The inner v is typed. It shadows the outer interface{} v. That's
// the idiomatic part.
case string:
buf.WriteString(v + "\n") // v is a string
case int:
buf.WriteString(fmt.Sprintln(v)) // v is an int
case float64:
buf.WriteString(fmt.Sprintln(v)) // v is a float64
}
}
return buf.String()
}
Run Code Online (Sandbox Code Playgroud)